home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / ld / dist / patch / ld.patch < prev   
Encoding:
Text File  |  1990-10-26  |  172.8 KB  |  6,391 lines

  1. /* Linker `ld' for GNU
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Richard Stallman with some help from Eric Albert.
  19.    Set, indirect, and warning symbol features added by Randy Smith.  */
  20.  
  21. #include <ar.h>
  22. #include <stdio.h>
  23. #include <sys/types.h>
  24. #include <sys/stat.h>
  25. #include <sys/file.h>
  26. #ifndef sony_news
  27. #include <fcntl.h>
  28. #endif
  29.  
  30. #define NO_C_PLUS_PLUS
  31.  
  32. #define TARGET_SUN2             2
  33. #define TARGET_SUN3             3
  34. #define TARGET_SUN4             4
  35. #define TARGET_ALTOS            5
  36. #define TARGET_I386             6   
  37. #define TARGET_HPUX             7
  38. #define TARGET_SONY_NEWS        8
  39. #define TARGET_SEQUENT          9
  40. #define TARGET_VAX              10
  41.  
  42. /*
  43.  * If `TARGET_MACHINE' was not defined on the compiler command line,
  44.  * then set it equal to the host machine.
  45.  */
  46. #ifndef TARGET_MACHINE
  47. #if defined(sun) && defined(sparc)
  48. #define TARGET_MACHINE  TARGET_SUN4
  49. #endif
  50. #if defined(sun) && (defined(m68020) || defined(mc68020))
  51. #define TARGET_MACHINE  TARGET_SUN3
  52. #endif
  53. #if defined(sun) && (defined(m68010) || defined(mc68010))
  54. #define TARGET_MACHINE  TARGET_SUN2
  55. #endif
  56. #if defined(ALTOS)
  57. #define TARGET_MACHINE  TARGET_ALTOS
  58. #endif
  59. #if defined(hpux)
  60. #define TARGET_MACHINE  TARGET_HPUX
  61. #endif
  62. #if defined(is386)
  63. #define TARGET_MACHINE  TARGET_I386
  64. #endif
  65. #if defined(sony_news)
  66. #define TARGET_MACHINE  TARGET_SONY_NEWS
  67. #endif
  68. #if defined(sequent)
  69. #define TARGET_MACHINE  TARGET_SEQUENT
  70. #endif
  71. #if defined(is68k) && !defined(TARGET_MACHINE)
  72. #define TARGET_MACHINE  TARGET_68K
  73. #endif
  74. #endif
  75.  
  76. #ifndef TARGET_MACHINE
  77.     CANNOT COMPILE, NO TARGET MACHINE SPECIFIED
  78. #endif
  79.  
  80. #ifndef BIG_ENDIAN
  81. #define BIG_ENDIAN      4321
  82. #endif
  83. #ifndef LITTLE_ENDIAN
  84. #define LITTLE_ENDIAN   1234
  85. #endif
  86. #ifndef PDP_ENDIAN
  87. /* I think it is unlikely that anybody will try to cross compile
  88.  * to or from a pdp, so only big-endian and little-endian are supported. */
  89. #define PDP_ENDIAN   3412
  90. #endif
  91.  
  92. #if TARGET_MACHINE==TARGET_SUN4         || \
  93.     TARGET_MACHINE==TARGET_SUN3         || \
  94.     TARGET_MACHINE==TARGET_SUN2         || \
  95.     TARGET_MACHINE==TARGET_ALTOS        || \
  96.     TARGET_MACHINE==TARGET_HPUX         || \
  97.     TARGET_MACHINE==TARGET_SONY_NEWS    || \
  98.     TARGET_MACHINE==TARGET_68K
  99. #define TARGET_BYTE_ORDER       BIG_ENDIAN
  100. #endif
  101.  
  102. #if TARGET_MACHINE==TARGET_VAX          || \
  103.     TARGET_MACHINE==TARGET_I386         || \
  104.     TARGET_MACHINE==TARGET_SEQUENT
  105. #define TARGET_BYTE_ORDER       LITTLE_ENDIAN
  106. #endif
  107.  
  108. #if TARGET_MACHINE==TARGET_SUN3
  109. #define TARGET_PAGE_SIZE    0x2000
  110. #endif
  111.  
  112. #if defined(sparc)      || \
  113.     defined(m68000)     || \
  114.     defined(mc68000)    || \
  115.     defined(m68010)     || \
  116.     defined(mc68010)    || \
  117.     defined(m68020)     || \
  118.     defined(mc68020)    || \
  119.     defined(is68k)      || \
  120.     defined(hpux)       || \
  121.     defined(sony_news)
  122. #define HOST_BYTE_ORDER     BIG_ENDIAN
  123. #endif
  124.  
  125. #if defined(vax)        || \
  126.     defined(is386)      || \
  127.     defined(ds3100)     || \
  128.     defined(sequent)
  129. #define HOST_BYTE_ORDER     LITTLE_ENDIAN
  130. #endif
  131.  
  132. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  133. static void fix_byte_order();
  134. static void fix_exec_header_byte_order();
  135. static void fix_symbol_byte_order();
  136. static void target_to_host_reloc_byte_order();
  137. static void host_to_target_reloc_byte_order();
  138. static void fix_symbol_root_byte_order();
  139. #endif
  140.  
  141. #ifdef COFF_ENCAPSULATE
  142. #include "a.out.encap.h"
  143. #else
  144. #ifdef sprite
  145. #if TARGET_MACHINE==TARGET_SUN4
  146. #include <sun4.md/a.out.h>
  147. #elif TARGET_MACHINE==TARGET_SUN3
  148. #include <sun3.md/a.out.h>
  149. #elif TARGET_MACHINE==TARGET_SEQUENT
  150. #include <symm.md/a.out.h>
  151. #else
  152.     no a.out.h specified
  153. #endif
  154. #else
  155. #include <a.out.h>
  156. #endif
  157. #endif
  158.  
  159. #ifdef sprite
  160. #undef NEW_SEG_SIZE
  161. #if TARGET_MACHINE==TARGET_SUN4
  162. #define NEW_SEG_SIZE    0x40000
  163. #endif
  164. #if TARGET_MACHINE==TARGET_SUN3
  165. #define NEW_SEG_SIZE    0x20000
  166. #endif
  167. #endif  /* sprite */
  168.  
  169. #ifndef N_SET_MAGIC
  170. #define N_SET_MAGIC(exec, val)  ((exec).a_magic = val)
  171. #endif
  172.  
  173. /* If compiled with GNU C, use the built-in alloca */
  174. #ifdef __GNUC__
  175. # define alloca __builtin_alloca
  176. #else
  177. # if defined(sun) && defined(sparc)
  178. #  include "alloca.h"
  179. # else
  180. char *alloca ();
  181. # endif
  182. #endif
  183.  
  184. #include "getopt.h"
  185.  
  186. /* Always use the GNU version of debugging symbol type codes, if possible.  */
  187.  
  188. #include "stab.h"
  189. #define CORE_ADDR unsigned long    /* For symseg.h */
  190. #include "symseg.h"
  191.  
  192. #ifdef USG
  193. #include <string.h>
  194. #else
  195. #include <strings.h>
  196. #endif
  197.  
  198. /* Determine whether we should attempt to handle (minimally)
  199.    N_BINCL and N_EINCL.  */
  200.  
  201. #if defined (__GNU_STAB__) || defined (N_BINCL)
  202. #define HAVE_SUN_STABS
  203. #endif
  204.  
  205. #define min(a,b) ((a) < (b) ? (a) : (b))
  206.  
  207. /* Macro to control the number of undefined references printed */
  208. #define MAX_UREFS_PRINTED    10
  209.  
  210. /* Size of a page; obtained from the operating system.  */
  211.  
  212. int page_size;
  213.  
  214. /* Name this program was invoked by.  */
  215.  
  216. char *progname;
  217.  
  218. /* System dependencies */
  219.  
  220. /* Define this if names etext, edata and end should not start with `_'.  */
  221. /* #define nounderscore 1 */
  222.  
  223. /* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
  224.    whose native format is different.  */
  225. /* #define NON_NATIVE */
  226.  
  227. /* Define this to specify the default executable format.  */
  228.  
  229. #if TARGET_MACHINE==TARGET_HPUX
  230. #define DEFAULT_MAGIC NMAGIC  /* hpux bugs screw ZMAGIC */
  231. #endif
  232.  
  233. #ifndef DEFAULT_MAGIC
  234. #define DEFAULT_MAGIC ZMAGIC
  235. #endif
  236.  
  237. /* Ordinary 4.3bsd lacks these macros in a.out.h.  */
  238.  
  239. #ifndef N_TXTADDR
  240. #if TARGET_MACHINE==TARGET_VAX || TARGET_MACHINE==TARGET_SONY_NEWS
  241. #define N_TXTADDR(X) 0
  242. #endif
  243. #if TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  244. #define N_TXTADDR(x)  (sizeof (struct exec))
  245. #endif
  246. #if TARGET_MACHINE==TARGET_SEQUENT
  247. #define    N_TXTADDR(x) (N_ADDRADJ(x))
  248. #endif
  249. #endif
  250.  
  251. #ifndef N_DATADDR
  252. #if TARGET_MACHINE==TARGET_VAX || TARGET_MACHINE==TARGET_SONY_NEWS
  253. #define N_DATADDR(x) \
  254.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  255.     : (page_size+((N_TXTADDR(x)+(x).a_text-1) & ~(page_size-1))))
  256. #endif
  257. #if TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  258. #define SEGMENT_SIZE 0x20000
  259. #define N_DATADDR(x) \
  260.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  261.      : (SEGMENT_SIZE + ((N_TXTADDR(x)+(x).a_text-1) & ~(SEGMENT_SIZE-1))))
  262. #endif
  263. #if TARGET_MACHINE==TARGET_SEQUENT
  264. #define N_DATADDR(x) \
  265.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  266.     : (page_size+(((x).a_text-1) & ~(page_size-1))))
  267. #endif
  268. #ifdef NeXT
  269. #define N_DATADDR(X) \
  270.     (((X).a_magic==ZMAGIC)?(N_TXTADDR(X)+(X).a_text+0xFFFF)&~0xFFFF \
  271.      :N_TXTADDR(X)+(X).a_text)
  272. #endif
  273. #endif
  274.  
  275. /* The "address" of the data segment in a relocatable file.
  276.    The text address of a relocatable file is always
  277.    considered to be zero (instead of the value of N_TXTADDR, which
  278.    is what the address is in an executable), so we need to subtract
  279.    N_TXTADDR from N_DATADDR to get the "address" for the input file.  */
  280. #define DATA_ADDR_DOT_O(hdr) (N_DATADDR(hdr) - N_TXTADDR(hdr))
  281.  
  282. /* Define how to initialize system-dependent header fields.  */
  283. #if TARGET_MACHINE==TARGET_SUN4
  284. #define INITIALIZE_HEADER \
  285.   {outheader.a_machtype = M_SPARC; outheader.a_toolversion = 1;}
  286. #endif
  287. #if TARGET_MACHINE==TARGET_SUN2
  288. #define INITIALIZE_HEADER outheader.a_machtype = M_68010
  289. #endif
  290. #if TARGET_MACHINE==TARGET_SUN3
  291. #define INITIALIZE_HEADER outheader.a_machtype = M_68020
  292. #endif
  293. #if TARGET_MACHINE==TARGET_ALTOS
  294. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_68020)
  295. #endif
  296. #if TARGET_MACHINE==TARGET_HPUX
  297. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, HP9000S200_ID)
  298. #endif
  299. #if TARGET_MACHINE==TARGET_I386
  300. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_386)
  301. #endif
  302. #if TARGET_MACHINE==TARGET_68K
  303. #define INITIALIZE_HEADER outheader.a_machtype = 0;  
  304. /* This enables code to take care of an ugly hack in the ISI OS.
  305.    If a symbol beings with _$, then the object file is included only
  306.    if the rest of the symbol name has been referenced. */
  307. #define DOLLAR_KLUDGE
  308. #endif
  309. #if TARGET==TARGET_SEQUENT
  310. /* This is all stuff needed to make standalone binaries */
  311. static struct gdtbl gdt_filler = {
  312.     { 0x0000FFFF, 0x00CF9A00 },    /* code entry */
  313.     { 0x0000FFFF, 0x00CF9200 },    /* data entry */
  314.     { 0x00180017, 0x00000000 },    /* 6 byte descriptor */
  315. };
  316.  
  317. static char instr[] = {
  318.     0x67, 0x66, 0x0f, 0x01, 0x15, 0x30, 0x00, 0x00, 0x00,
  319.     0x0f, 0x20, 0xc3,
  320.     0x80, 0xcb, 0x01,
  321.     0x0f, 0x22, 0xc3,
  322.     0xea, 0x5b, 0x00, 0x08, 0x00,
  323.     0xbb, 0x10, 0x00, 0x00, 0x00,
  324.     0x8e, 0xdb,
  325.     0x8e, 0xd3,
  326.     0x8e, 0xc3,
  327.     0xff, 0x25, 0x6c, 0x00, 0x00, 0x00,
  328.     0x00, 0x00, 0x00, 0x00, };
  329. #endif   
  330.  
  331. /* Values for 3rd argument to lseek().  */
  332. #ifndef L_SET
  333. #define L_SET 0
  334. #endif
  335. /* This is called L_INCR in BSD, but SEEK_CUR in POSIX.  */
  336. #ifndef SEEK_CUR
  337. #define SEEK_CUR 1
  338. #endif
  339.  
  340. /*
  341.  * Ok.  Following are the relocation information macros.  If your
  342.  * system cannot use the default set (below), you must define all of these:
  343.  
  344.  *   relocation_info: This must be typedef'd (or #define'd) to the type
  345.  * of structure that is stored in the relocation info section of your
  346.  * a.out files.  Often this is defined in the a.out.h for your system.
  347.  *
  348.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  349.  * <whatever> to be relocated.  *Must be an lvalue*.
  350.  *
  351.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  352.  * external symbol (1), or was it fully resolved upon entering the
  353.  * loader (0) in which case some combination of the value in memory
  354.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  355.  * what the value of the relocation actually was.  *Must be an lvalue*.
  356.  *
  357.  *   RELOC_TYPE (rval): For a non-external relocation, this is the
  358.  * segment to relocate for.  *Must be an lvalue.*
  359.  *
  360.  *   RELOC_SYMBOL (rval): For an external relocation, this is the
  361.  * index of its symbol in the symbol table.  *Must be an lvalue*.
  362.  *
  363.  *   RELOC_MEMORY_ADD_P (rval): This should be 1 if the final
  364.  * relocation value output here should be added to memory; 0, if the
  365.  * section of memory described should simply be set to the relocation
  366.  * value.
  367.  *
  368.  *   RELOC_MEMORY_ADD_P (rval): If this is nonzero, the value previously
  369.  * present in the memory location to be relocated is *added*
  370.  * to the relocation value, to produce the final result.
  371.  * Otherwise, the relocation value is stored in the memory location
  372.  * and the value previously found there is ignored.
  373.  * By default, this is always 1.
  374.  *
  375.  *   RELOC_MEMORY_SUB_P (rval): If this is nonzero, the value previously
  376.  * present in the memory location to be relocated is *subtracted*
  377.  * from the relocation value, to produce the final result.
  378.  * By default, this is always 0.
  379.  *
  380.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  381.  * an extra value to be added to the relocation value based on the
  382.  * individual relocation entry.  *Must be an lvalue if defined*.
  383.  *
  384.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  385.  * pc relative.
  386.  *
  387.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  388.  * final relocation value before putting it where it belongs.
  389.  *
  390.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  391.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  392.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  393.  * do everything in terms of the bit operators below), but having this
  394.  * macro could end up producing better code on machines without fancy
  395.  * bit twiddling.  Also, it's easier to understand/code big/little
  396.  * endian distinctions with this macro.
  397.  *
  398.  *   RELOC_TARGET_BITPOS (rval): The starting bit position within the
  399.  * object described in RELOC_TARGET_SIZE in which the relocation value
  400.  * will go.
  401.  *
  402.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  403.  * with the bits of the relocation value.  It may be assumed by the
  404.  * code that the relocation value will fit into this many bits.  This
  405.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  406.  *
  407.  *
  408.  *        Things I haven't implemented
  409.  *        ----------------------------
  410.  *
  411.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  412.  *
  413.  *    Pc relative relocation for External references.
  414.  *
  415.  *
  416.  */
  417.  
  418. #if TARGET_MACHINE==TARGET_SUN4
  419. /* Sparc (Sun 4) macros */
  420. #undef relocation_info
  421. #define relocation_info                    reloc_info_sparc
  422. #define RELOC_ADDRESS(r)        ((r)->r_address)                 
  423. #define RELOC_EXTERN_P(r)               ((r)->r_extern)      
  424. #define RELOC_TYPE(r)                   ((r)->r_index)  
  425. #define RELOC_SYMBOL(r)                 ((r)->r_index)   
  426. #define RELOC_MEMORY_SUB_P(r)        0
  427. #define RELOC_MEMORY_ADD_P(r)           0
  428. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)       
  429. #define RELOC_PCREL_P(r)                \
  430.     ((int) (r)->r_type >= (int) RELOC_DISP8 && \
  431.      (int) (r)->r_type <= (int) RELOC_WDISP22)
  432. #define RELOC_VALUE_RIGHTSHIFT(r) \
  433.     (reloc_target_rightshift[(int) (r)->r_type])
  434. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(int) (r)->r_type])
  435. #define RELOC_TARGET_BITPOS(r)          0
  436. #define RELOC_TARGET_BITSIZE(r) \
  437.     (reloc_target_bitsize[(int) (r)->r_type])
  438.  
  439. /* Note that these are very dependent on the order of the enums in
  440.    enum reloc_type (in a.out.h); if they change the following must be
  441.    changed */
  442. /* Also note that the last few may be incorrect; I have no information */
  443. static int reloc_target_rightshift[] = {
  444.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  445. };
  446. static int reloc_target_size[] = {
  447.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  448. };
  449. static int reloc_target_bitsize[] = {
  450.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  451. };
  452.  
  453. #define    MAX_ALIGNMENT    (sizeof (double))
  454.   /* The pagesize on an old sun4 is 0x2000, on sparcStation it is 0x1000.
  455.      If you want to use the same binaries on both, then you need to use
  456.      the larger pagesize. */
  457. #define TARGET_PAGE_SIZE    0x2000
  458. #endif
  459.  
  460. #if TARGET_MACHINE==TARGET_SEQUENT
  461. #define RELOC_ADDRESS(r)        ((r)->r_address)
  462. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  463. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  464. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  465. #define RELOC_MEMORY_SUB_P(r)    ((r)->r_bsr)
  466. #define RELOC_MEMORY_ADD_P(r)    1
  467. #undef RELOC_ADD_EXTRA
  468. #define RELOC_PCREL_P(r)        ((r)->r_pcrel || (r)->r_bsr)
  469. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  470. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  471. #define RELOC_TARGET_BITPOS(r)    0
  472. #define RELOC_TARGET_BITSIZE(r)    32
  473. #define TARGET_PAGE_SIZE    0x1000
  474. #endif
  475.  
  476. /* Default macros */
  477. #ifndef RELOC_ADDRESS
  478. #define RELOC_ADDRESS(r)        ((r)->r_address)
  479. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  480. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  481. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  482. #define RELOC_MEMORY_SUB_P(r)    0
  483. #define RELOC_MEMORY_ADD_P(r)    1
  484. #undef RELOC_ADD_EXTRA
  485. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  486. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  487. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  488. #define RELOC_TARGET_BITPOS(r)    0
  489. #define RELOC_TARGET_BITSIZE(r)    32
  490. #endif
  491.  
  492. #ifndef MAX_ALIGNMENT
  493. #define    MAX_ALIGNMENT    (sizeof (int))
  494. #endif
  495.  
  496. #ifdef nounderscore
  497. #define LPREFIX '.'
  498. #else
  499. #define LPREFIX 'L'
  500. #endif
  501.  
  502.  
  503. /* Special global symbol types understood by GNU LD.  */
  504.  
  505. /* The following type indicates the definition of a symbol as being
  506.    an indirect reference to another symbol.  The other symbol
  507.    appears as an undefined reference, immediately following this symbol.
  508.  
  509.    Indirection is asymmetrical.  The other symbol's value will be used
  510.    to satisfy requests for the indirect symbol, but not vice versa.
  511.    If the other symbol does not have a definition, libraries will
  512.    be searched to find a definition.
  513.  
  514.    So, for example, the following two lines placed in an assembler
  515.    input file would result in an object file which would direct gnu ld
  516.    to resolve all references to symbol "foo" as references to symbol
  517.    "bar".
  518.  
  519.     .stabs "_foo",11,0,0,0
  520.     .stabs "_bar",1,0,0,0
  521.  
  522.    Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)).  */
  523.  
  524. #ifndef N_INDR
  525. #define N_INDR 0xa
  526. #endif
  527.  
  528. /* The following symbols refer to set elements.  These are expected
  529.    only in input to the loader; they should not appear in loader
  530.    output (unless relocatable output is requested).  To be recognized
  531.    by the loader, the input symbols must have their N_EXT bit set.
  532.    All the N_SET[ATDB] symbols with the same name form one set.  The
  533.    loader collects all of these elements at load time and outputs a
  534.    vector for each name.
  535.    Space (an array of 32 bit words) is allocated for the set in the
  536.    data section, and the n_value field of each set element value is
  537.    stored into one word of the array.
  538.    The first word of the array is the length of the set (number of
  539.    elements).  The last word of the vector is set to zero for possible
  540.    use by incremental loaders.  The array is ordered by the linkage
  541.    order; the first symbols which the linker encounters will be first
  542.    in the array.
  543.  
  544.    In C syntax this looks like:
  545.  
  546.     struct set_vector {
  547.       unsigned int length;
  548.       unsigned int vector[length];
  549.       unsigned int always_zero;
  550.     };
  551.  
  552.    Before being placed into the array, each element is relocated
  553.    according to its type.  This allows the loader to create an array
  554.    of pointers to objects automatically.  N_SETA type symbols will not
  555.    be relocated.
  556.  
  557.    The address of the set is made into an N_SETV symbol
  558.    whose name is the same as the name of the set.
  559.    This symbol acts like a N_DATA global symbol
  560.    in that it can satisfy undefined external references.
  561.  
  562.    For the purposes of determining whether or not to load in a library
  563.    file, set element definitions are not considered "real
  564.    definitions"; they will not cause the loading of a library
  565.    member.
  566.  
  567.    If relocatable output is requested, none of this processing is
  568.    done.  The symbols are simply relocated and passed through to the
  569.    output file.
  570.  
  571.    So, for example, the following three lines of assembler code
  572.    (whether in one file or scattered between several different ones)
  573.    will produce a three element vector (total length is five words;
  574.    see above), referenced by the symbol "_xyzzy", which will have the
  575.    addresses of the routines _init1, _init2, and _init3.
  576.  
  577.    *NOTE*: If symbolic addresses are used in the n_value field of the
  578.    defining .stabs, those symbols must be defined in the same file as
  579.    that containing the .stabs.
  580.  
  581.     .stabs "_xyzzy",23,0,0,_init1
  582.     .stabs "_xyzzy",23,0,0,_init2
  583.     .stabs "_xyzzy",23,0,0,_init3
  584.  
  585.    Note that (23 == (N_SETT | N_EXT)).  */
  586.  
  587. #ifndef N_SETA
  588. #define    N_SETA    0x14        /* Absolute set element symbol */
  589. #endif                /* This is input to LD, in a .o file.  */
  590.  
  591. #ifndef N_SETT
  592. #define    N_SETT    0x16        /* Text set element symbol */
  593. #endif                /* This is input to LD, in a .o file.  */
  594.  
  595. #ifndef N_SETD
  596. #define    N_SETD    0x18        /* Data set element symbol */
  597. #endif                /* This is input to LD, in a .o file.  */
  598.  
  599. #ifndef N_SETB
  600. #define    N_SETB    0x1A        /* Bss set element symbol */
  601. #endif                /* This is input to LD, in a .o file.  */
  602.  
  603. /* Macros dealing with the set element symbols defined in a.out.h */
  604. #define    SET_ELEMENT_P(x)    ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
  605. #define TYPE_OF_SET_ELEMENT(x)    ((x)-N_SETA+N_ABS)
  606.  
  607. #ifndef N_SETV
  608. #define N_SETV    0x1C        /* Pointer to set vector in data area.  */
  609. #endif                /* This is output from LD.  */
  610.  
  611. /* If a this type of symbol is encountered, its name is a warning
  612.    message to print each time the symbol referenced by the next symbol
  613.    table entry is referenced.
  614.  
  615.    This feature may be used to allow backwards compatibility with
  616.    certain functions (eg. gets) but to discourage programmers from
  617.    their use.
  618.  
  619.    So if, for example, you wanted to have ld print a warning whenever
  620.    the function "gets" was used in their C program, you would add the
  621.    following to the assembler file in which gets is defined:
  622.  
  623.     .stabs "Obsolete function \"gets\" referenced",30,0,0,0
  624.     .stabs "_gets",1,0,0,0
  625.  
  626.    These .stabs do not necessarily have to be in the same file as the
  627.    gets function, they simply must exist somewhere in the compilation.  */
  628.  
  629. #ifndef N_WARNING
  630. #define N_WARNING 0x1E        /* Warning message to print if symbol
  631.                    included */
  632. #endif                /* This is input to ld */
  633.  
  634. #ifndef __GNU_STAB__
  635.  
  636. /* Line number for the data section.  This is to be used to describe
  637.    the source location of a variable declaration.  */
  638. #ifndef N_DSLINE
  639. #define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
  640. #endif
  641.  
  642. /* Line number for the bss section.  This is to be used to describe
  643.    the source location of a variable declaration.  */
  644. #ifndef N_BSLINE
  645. #define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
  646. #endif
  647.  
  648. #endif /* not __GNU_STAB__ */
  649.  
  650. /* Symbol table */
  651.  
  652. /* Global symbol data is recorded in these structures,
  653.    one for each global symbol.
  654.    They are found via hashing in 'symtab', which points to a vector of buckets.
  655.    Each bucket is a chain of these structures through the link field.  */
  656.  
  657. typedef
  658.   struct glosym
  659.     {
  660.       /* Pointer to next symbol in this symbol's hash bucket.  */
  661.       struct glosym *link;
  662.       /* Name of this symbol.  */
  663.       char *name;
  664.       /* Value of this symbol as a global symbol.  */
  665.       long value;
  666.       /* Chain of external 'nlist's in files for this symbol, both defs
  667.      and refs.  */
  668.       struct nlist *refs;
  669.       /* Any warning message that might be associated with this symbol
  670.          from an N_WARNING symbol encountered. */
  671.       char *warning;
  672.       /* Nonzero means definitions of this symbol as common have been seen,
  673.      and the value here is the largest size specified by any of them.  */
  674.       int max_common_size;
  675.       /* For OUTPUT_RELOCATABLE, records the index of this global sym in the
  676.      symbol table to be written, with the first global sym given index 0.*/
  677.       int def_count;
  678.       /* Nonzero means a definition of this global symbol is known to exist.
  679.      Library members should not be loaded on its account.  */
  680.       char defined;
  681.       /* Nonzero means a reference to this global symbol has been seen
  682.      in a file that is surely being loaded.
  683.      A value higher than 1 is the n_type code for the symbol's
  684.      definition.  */
  685.       char referenced;
  686.       /* A count of the number of undefined references printed for a
  687.      specific symbol.  If a symbol is unresolved at the end of
  688.      digest_symbols (and the loading run is supposed to produce
  689.      relocatable output) do_file_warnings keeps track of how many
  690.      unresolved reference error messages have been printed for
  691.      each symbol here.  When the number hits MAX_UREFS_PRINTED,
  692.      messages stop. */
  693.       unsigned char undef_refs;
  694.       /* 1 means that this symbol has multiple definitions.  2 means
  695.          that it has multiple definitions, and some of them are set
  696.      elements, one of which has been printed out already.  */
  697.       unsigned char multiply_defined;
  698.       /* Nonzero means print a message at all refs or defs of this symbol */
  699.       char trace;
  700.     }
  701.   symbol;
  702.  
  703. #ifndef NO_C_PLUS_PLUS
  704. /* Demangler for C++. */
  705. extern char *cplus_demangle ();
  706. #endif /* NO_C_PLUS_PLUS */
  707.  
  708. /* Demangler function to use. */
  709. char *(*demangler)() = NULL;
  710.  
  711.  
  712. /* Demangler for C++.  */
  713. extern char *cplus_demangle ();
  714.  
  715. /* Demangler function to use.  We unconditionally enable the C++ demangler
  716.    because we assume any name it successfully demangles was probably produced
  717.    by the C++ compiler.  Enabling it only if -lg++ was specified seems too
  718.    much of a kludge.  */
  719. char *(*demangler)() = cplus_demangle;
  720.  
  721. /* Number of buckets in symbol hash table */
  722. #define    TABSIZE    1009
  723.  
  724. /* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
  725. symbol *symtab[TABSIZE];
  726.  
  727. /* Number of symbols in symbol hash table. */
  728. int num_hash_tab_syms = 0;
  729.  
  730. /* Count the number of nlist entries that are for local symbols.
  731.    This count and the three following counts
  732.    are incremented as as symbols are entered in the symbol table.  */
  733. int local_sym_count;
  734.  
  735. /* Count number of nlist entries that are for local symbols
  736.    whose names don't start with L. */
  737. int non_L_local_sym_count;
  738.  
  739. /* Count the number of nlist entries for debugger info.  */
  740. int debugger_sym_count;
  741.  
  742. /* Count the number of global symbols referenced and not defined.  */
  743. int undefined_global_sym_count;
  744.  
  745. /* Count the number of global symbols multiply defined.  */
  746. int multiple_def_count;
  747.  
  748. /* Count the number of defined global symbols.
  749.    Each symbol is counted only once
  750.    regardless of how many different nlist entries refer to it,
  751.    since the output file will need only one nlist entry for it.
  752.    This count is computed by `digest_symbols';
  753.    it is undefined while symbols are being loaded. */
  754. int defined_global_sym_count;
  755.  
  756. /* Count the number of symbols defined through common declarations.
  757.    This count is kept in symdef_library, linear_library, and
  758.    enter_global_ref.  It is incremented when the defined flag is set
  759.    in a symbol because of a common definition, and decremented when
  760.    the symbol is defined "for real" (ie. by something besides a common
  761.    definition).  */
  762. int common_defined_global_count;
  763.  
  764. /* Count the number of set element type symbols and the number of
  765.    separate vectors which these symbols will fit into.  See the
  766.    GNU a.out.h for more info.
  767.    This count is computed by 'enter_file_symbols' */
  768. int set_symbol_count;
  769. int set_vector_count;
  770.  
  771. /* Define a linked list of strings which define symbols which should
  772.    be treated as set elements even though they aren't.  Any symbol
  773.    with a prefix matching one of these should be treated as a set
  774.    element.
  775.  
  776.    This is to make up for deficiencies in many assemblers which aren't
  777.    willing to pass any stabs through to the loader which they don't
  778.    understand.  */
  779. struct string_list_element {
  780.   char *str;
  781.   struct string_list_element *next;
  782. };
  783.  
  784. struct string_list_element *set_element_prefixes;
  785.  
  786. /* Count the number of definitions done indirectly (ie. done relative
  787.    to the value of some other symbol. */
  788. int global_indirect_count;
  789.  
  790. /* Count the number of warning symbols encountered. */
  791. int warning_count;
  792.  
  793. /* Total number of symbols to be written in the output file.
  794.    Computed by digest_symbols from the variables above.  */
  795. int nsyms;
  796.  
  797.  
  798. /* Nonzero means ptr to symbol entry for symbol to use as start addr.
  799.    -e sets this.  */
  800. symbol *entry_symbol;
  801.  
  802. /* These can be NULL if we don't actually have such a symbol.  */
  803. symbol *edata_symbol;   /* the symbol _edata */
  804. symbol *etext_symbol;   /* the symbol _etext */
  805. symbol *end_symbol;    /* the symbol _end */
  806. /* We also need __{edata,etext,end} so that they can safely
  807.    be used from an ANSI library.  */
  808. symbol *edata_symbol_alt;
  809. symbol *etext_symbol_alt;
  810. symbol *end_symbol_alt;
  811.  
  812. /* Kinds of files potentially understood by the linker. */
  813.  
  814. enum file_type { IS_UNKNOWN, IS_ARCHIVE, IS_A_OUT, IS_MACH_O };
  815.  
  816. /* Each input file, and each library member ("subfile") being loaded,
  817.    has a `file_entry' structure for it.
  818.  
  819.    For files specified by command args, these are contained in the vector
  820.    which `file_table' points to.
  821.  
  822.    For library members, they are dynamically allocated,
  823.    and chained through the `chain' field.
  824.    The chain is found in the `subfiles' field of the `file_entry'.
  825.    The `file_entry' objects for the members have `superfile' fields pointing
  826.    to the one for the library.  */
  827.  
  828. struct file_entry {
  829.   /* Name of this file.  */
  830.   char *filename;
  831.  
  832.   /* What kind of file this is. */
  833.   enum file_type file_type;
  834.  
  835.   /* Name to use for the symbol giving address of text start */
  836.   /* Usually the same as filename, but for a file spec'd with -l
  837.      this is the -l switch itself rather than the filename.  */
  838.   char *local_sym_name;
  839.  
  840.   /* Describe the layout of the contents of the file.  */
  841.  
  842.   /* The text section. */
  843.   unsigned long int orig_text_address;
  844.   unsigned long int text_size;
  845.   long int text_offset;
  846.  
  847.   /* Text relocation. */
  848.   unsigned long int text_reloc_size;
  849.   long int text_reloc_offset;
  850.  
  851.   /* The data section. */
  852.   unsigned long int orig_data_address;
  853.   unsigned long int data_size;
  854.   long int data_offset;
  855.  
  856.   /* Data relocation. */
  857.   unsigned long int data_reloc_size;
  858.   long int data_reloc_offset;
  859.  
  860.   /* The bss section. */
  861.   unsigned long int orig_bss_address;
  862.   unsigned long int bss_size;
  863.  
  864.   /* The symbol and string tables. */
  865.   unsigned long int syms_size;
  866.   long int syms_offset;
  867.   unsigned long int strs_size;
  868.   long int strs_offset;
  869.  
  870.   /* The GDB symbol segment, if any. */
  871.   unsigned long int symseg_size;
  872.   long int symseg_offset;
  873.  
  874. #ifdef MACH_O
  875.   /* Section ordinals from the Mach-O load commands.  These
  876.      are compared with the n_sect fields of symbols.  */
  877.   int text_ordinal;
  878.   int data_ordinal;
  879.   int bss_ordinal;
  880. #endif
  881.  
  882.   /* Describe data from the file loaded into core */
  883.  
  884.   /* Symbol table of the file.  */
  885.   struct nlist *symbols;
  886.  
  887.   /* Pointer to the string table.
  888.      The string table is not kept in core all the time,
  889.      but when it is in core, its address is here.  */
  890.   char *strings;
  891.  
  892.   /* Next two used only if OUTPUT_RELOCATABLE or if needed for */
  893.   /* output of undefined reference line numbers. */
  894.  
  895.   /* Text reloc info saved by `write_text' for `coptxtrel'.  */
  896.   struct relocation_info *textrel;
  897.   /* Data reloc info saved by `write_data' for `copdatrel'.  */
  898.   struct relocation_info *datarel;
  899.  
  900.   /* Relation of this file's segments to the output file */
  901.  
  902.   /* Start of this file's text seg in the output file core image.  */
  903.   int text_start_address;
  904.   /* Start of this file's data seg in the output file core image.  */
  905.   int data_start_address;
  906.   /* Start of this file's bss seg in the output file core image.  */
  907.   int bss_start_address;
  908.   /* Offset in bytes in the output file symbol table
  909.      of the first local symbol for this file.  Set by `write_file_symbols'.  */
  910.   int local_syms_offset;
  911.  
  912.   /* For library members only */
  913.  
  914.   /* For a library, points to chain of entries for the library members.  */
  915.   struct file_entry *subfiles;
  916.   /* For a library member, offset of the member within the archive.
  917.      Zero for files that are not library members.  */
  918.   int starting_offset;
  919.   /* Size of contents of this file, if library member.  */
  920.   int total_size;
  921.   /* For library member, points to the library's own entry.  */
  922.   struct file_entry *superfile;
  923.   /* For library member, points to next entry for next member.  */
  924.   struct file_entry *chain;
  925.  
  926.   /* 1 if file is a library. */
  927.   char library_flag;
  928.  
  929.   /* 1 if file's header has been read into this structure.  */
  930.   char header_read_flag;
  931.  
  932.   /* 1 means search a set of directories for this file.  */
  933.   char search_dirs_flag;
  934.  
  935.   /* 1 means this is base file of incremental load.
  936.      Do not load this file's text or data.
  937.      Also default text_start to after this file's bss. */
  938.   char just_syms_flag;
  939. };
  940.  
  941. /* Vector of entries for input files specified by arguments.
  942.    These are all the input files except for members of specified libraries.  */
  943. struct file_entry *file_table;
  944.  
  945. /* Length of that vector.  */
  946. int number_of_files;
  947.  
  948. /* When loading the text and data, we can avoid doing a close
  949.    and another open between members of the same library.
  950.  
  951.    These two variables remember the file that is currently open.
  952.    Both are zero if no file is open.
  953.  
  954.    See `each_file' and `file_close'.  */
  955.  
  956. struct file_entry *input_file;
  957. int input_desc;
  958.  
  959. /* The name of the file to write; "a.out" by default.  */
  960.  
  961. char *output_filename;
  962.  
  963. /* What kind of output file to write.  */
  964.  
  965. enum file_type output_file_type;
  966.  
  967. #ifndef DEFAULT_OUTPUT_FILE_TYPE
  968. #ifdef MACH_O
  969. #define DEFAULT_OUTPUT_FILE_TYPE IS_MACH_O
  970. #else
  971. #define DEFAULT_OUTPUT_FILE_TYPE IS_A_OUT
  972. #endif
  973. #endif
  974.  
  975. /* What `style' of output file to write.  For BSD a.out files
  976.    this specifies OMAGIC, NMAGIC, or ZMAGIC.  For Mach-O files
  977.    this switches between MH_OBJECT and two flavors of MH_EXECUTE.  */
  978.  
  979. enum output_style
  980.   {
  981.     OUTPUT_UNSPECIFIED,
  982.     OUTPUT_RELOCATABLE,        /* -r */
  983.     OUTPUT_WRITABLE_TEXT,    /* -N */
  984.     OUTPUT_READONLY_TEXT,    /* -n */
  985.     OUTPUT_DEMAND_PAGED        /* -Z (default) */
  986.   };
  987.  
  988. enum output_style output_style;
  989.  
  990. #ifndef DEFAULT_OUTPUT_STYLE
  991. #define DEFAULT_OUTPUT_STYLE OUTPUT_DEMAND_PAGED
  992. #endif
  993.  
  994. /* Descriptor for writing that file with `mywrite'.  */
  995.  
  996. int outdesc;
  997.  
  998. /* The following are computed by `digest_symbols'.  */
  999.  
  1000. int text_size;            /* total size of text of all input files.  */
  1001. int text_header_size;        /* size of the file header if included in the
  1002.                    text size.  */
  1003. int data_size;            /* total size of data of all input files.  */
  1004. int bss_size;            /* total size of bss of all input files.  */
  1005. int text_reloc_size;        /* total size of text relocation of all input files.  */
  1006. int data_reloc_size;        /* total size of data relocation of all input
  1007.                    files.  */
  1008.   
  1009. /* The following are computed by write_header().  */
  1010. long int output_text_offset;    /* file offset of the text section.  */
  1011. long int output_data_offset;    /* file offset of the data section.  */
  1012. long int output_trel_offset;    /* file offset of the text relocation info.  */
  1013. long int output_drel_offset;    /* file offset of the data relocation info.  */
  1014. long int output_syms_offset;    /* file offset of the symbol table.  */
  1015. long int output_strs_offset;    /* file offset of the string table.  */
  1016.  
  1017. /* The following are incrementally computed by write_syms(); we keep
  1018.    them here so we can examine their values afterwards.  */
  1019. unsigned int output_syms_size;    /* total bytes of symbol table output. */
  1020. unsigned int output_strs_size;    /* total bytes of string table output. */
  1021.  
  1022. /* This can only be computed after the size of the string table is known.  */
  1023. long int output_symseg_offset;    /* file offset of the symbol segment (if any).  */
  1024.  
  1025. /* Incrementally computed by write_file_symseg().  */
  1026. unsigned int output_symseg_size;
  1027.  
  1028. /* Specifications of start and length of the area reserved at the end
  1029.    of the text segment for the set vectors.  Computed in 'digest_symbols' */
  1030. int set_sect_start;
  1031. int set_sect_size;
  1032.  
  1033. /* Pointer for in core storage for the above vectors, before they are
  1034.    written. */
  1035. unsigned long *set_vectors;
  1036.  
  1037. /* Amount of cleared space to leave at the end of the text segment.  */
  1038.  
  1039. int text_pad;
  1040.  
  1041. /* Amount of padding at end of data segment.  This has two parts:
  1042.    That which is before the bss segment, and that which overlaps
  1043.    with the bss segment.  */
  1044. int data_pad;
  1045.  
  1046. /* Format of __.SYMDEF:
  1047.    First, a longword containing the size of the 'symdef' data that follows.
  1048.    Second, zero or more 'symdef' structures.
  1049.    Third, a longword containing the length of symbol name strings.
  1050.    Fourth, zero or more symbol name strings (each followed by a null).  */
  1051.  
  1052. struct symdef {
  1053.   int symbol_name_string_index;
  1054.   int library_member_offset;
  1055. };
  1056.  
  1057. /* Record most of the command options.  */
  1058.  
  1059. /* Address we assume the text section will be loaded at.
  1060.    We relocate symbols and text and data for this, but we do not
  1061.    write any padding in the output file for it.  */
  1062. int text_start;
  1063.  
  1064. /* Address we decide the data section will be loaded at.  */
  1065. int data_start;
  1066.  
  1067. /* Nonzero if -T was specified in the command line.
  1068.    This prevents text_start from being set later to default values.  */
  1069. int T_flag_specified;
  1070.  
  1071. /* Nonzero if -Tdata was specified in the command line.
  1072.    This prevents data_start from being set later to default values.  */
  1073. int Tdata_flag_specified;
  1074.  
  1075. /* Size to pad data section up to.
  1076.    We simply increase the size of the data section, padding with zeros,
  1077.    and reduce the size of the bss section to match.  */
  1078. int specified_data_size;
  1079.  
  1080. /* Gap to insert between end of bss and start of data seg */
  1081. int data_gap;
  1082.  
  1083. /* Nonzero if -Z was specified (for data_gap) */
  1084. int Z_flag_specified;
  1085.  
  1086. /* Nonzero means print names of input files as processed.  */
  1087. int trace_files;
  1088.  
  1089. /* Which symbols should be stripped (omitted from the output):
  1090.    none, all, or debugger symbols.  */
  1091. enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
  1092.  
  1093. /* Which local symbols should be omitted:
  1094.    none, all, or those starting with L.
  1095.    This is irrelevant if STRIP_NONE.  */
  1096. enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
  1097.  
  1098. /* 1 => write load map.  */
  1099. int write_map;
  1100.  
  1101. /* 1 => assign space to common symbols even if OUTPUT_RELOCATABLE. */
  1102. int force_common_definition;
  1103.  
  1104. /* Standard directories to search for files specified by -l.  */
  1105. char *standard_search_dirs[] =
  1106. #ifdef STANDARD_SEARCH_DIRS
  1107.   {STANDARD_SEARCH_DIRS};
  1108. #else
  1109. #ifdef NON_NATIVE
  1110.   {"/usr/local/lib/gnu"};
  1111. #else
  1112.   {"/lib", "/usr/lib", "/usr/local/lib"};
  1113. #endif
  1114. #endif
  1115.  
  1116. /* If set STANDARD_SEARCH_DIRS is not searched.  */
  1117. int no_standard_dirs;
  1118.  
  1119. /* Actual vector of directories to search;
  1120.    this contains those specified with -L plus the standard ones.  */
  1121. char **search_dirs;
  1122.  
  1123. /* Length of the vector `search_dirs'.  */
  1124. int n_search_dirs;
  1125.  
  1126. /* Non zero means to create the output executable.
  1127.    Cleared by nonfatal errors.  */
  1128. int make_executable;
  1129.  
  1130. /* Force the executable to be output, even if there are non-fatal
  1131.    errors */
  1132. int force_executable;
  1133.  
  1134. /* Keep a list of any symbols referenced from the command line (so
  1135.    that error messages for these guys can be generated). This list is
  1136.    zero terminated. */
  1137. struct glosym **cmdline_references;
  1138. int cl_refs_allocated;
  1139.  
  1140. #ifndef bcopy
  1141. void bcopy (), bzero ();
  1142. #endif
  1143. char *malloc (), *realloc ();
  1144. void free ();
  1145.  
  1146. char *xmalloc ();
  1147. char *xrealloc ();
  1148. void usage ();
  1149. void fatal ();
  1150. void fatal_with_file ();
  1151. void perror_name ();
  1152. void perror_file ();
  1153. void error ();
  1154.  
  1155. int parse ();
  1156. void initialize_text_start ();
  1157. void initialize_data_start ();
  1158. void digest_symbols ();
  1159. void print_symbols ();
  1160. void load_symbols ();
  1161. void decode_command ();
  1162. void list_undefined_symbols ();
  1163. void list_unresolved_references ();
  1164. void write_output ();
  1165. void write_header ();
  1166. void write_text ();
  1167. void read_file_relocation ();
  1168. void write_data ();
  1169. void write_rel ();
  1170. void write_syms ();
  1171. void write_symsegs ();
  1172. void mywrite ();
  1173. void symtab_init ();
  1174. void padfile ();
  1175. char *concat ();
  1176. char *get_file_name ();
  1177. symbol *getsym (), *getsym_soft ();
  1178.  
  1179. int
  1180. main (argc, argv)
  1181.      char **argv;
  1182.      int argc;
  1183. {
  1184. /*   Added this to stop ld core-dumping on very large .o files.    */
  1185. #ifdef RLIMIT_STACK
  1186.   /* Get rid of any avoidable limit on stack size.  */
  1187.   {
  1188.       struct rlimit rlim;
  1189.  
  1190.       /* Set the stack limit huge so that alloca does not fail. */
  1191.       getrlimit (RLIMIT_STACK, &rlim);
  1192.       rlim.rlim_cur = rlim.rlim_max;
  1193.       setrlimit (RLIMIT_STACK, &rlim);
  1194.   }
  1195. #endif /* RLIMIT_STACK */
  1196.  
  1197. #ifdef TARGET_PAGE_SIZE
  1198.   page_size = TARGET_PAGE_SIZE;
  1199. #else
  1200.   page_size = getpagesize ();
  1201. #endif
  1202.  
  1203.   progname = argv[0];
  1204.  
  1205. #ifdef RLIMIT_STACK
  1206.   /* Avoid dumping core on large .o files.  */
  1207.   {
  1208.     struct rlimit rl;
  1209.  
  1210.     getrlimit (RLIMIT_STACK, &rl);
  1211.     rl.rlim_cur = rl.rlim_max;
  1212.     setrlimit (RLIMIT_STACK, &rl);
  1213.   }
  1214. #endif
  1215.  
  1216.   /* Clear the cumulative info on the output file.  */
  1217.   text_size = 0;
  1218.   data_size = 0;
  1219.   bss_size = 0;
  1220.   text_reloc_size = 0;
  1221.   data_reloc_size = 0;
  1222.  
  1223.   data_pad = 0;
  1224.   text_pad = 0;
  1225.  
  1226.   /* Initialize the data about options.  */
  1227.  
  1228.   specified_data_size = 0;
  1229.   strip_symbols = STRIP_NONE;
  1230.   trace_files = 0;
  1231.   discard_locals = DISCARD_NONE;
  1232.   entry_symbol = 0;
  1233.   write_map = 0;
  1234.   force_common_definition = 0;
  1235.   T_flag_specified = 0;
  1236.   Tdata_flag_specified = 0;
  1237.   make_executable = 1;
  1238.   force_executable = 0;
  1239.   set_element_prefixes = 0;
  1240.   Z_flag_specified = 0;
  1241.  
  1242.   /* Initialize the cumulative counts of symbols.  */
  1243.  
  1244.   local_sym_count = 0;
  1245.   non_L_local_sym_count = 0;
  1246.   debugger_sym_count = 0;
  1247.   undefined_global_sym_count = 0;
  1248.   set_symbol_count = 0;
  1249.   set_vector_count = 0;
  1250.   global_indirect_count = 0;
  1251.   warning_count = 0;
  1252.   multiple_def_count = 0;
  1253.   common_defined_global_count = 0;
  1254.  
  1255.   /* Keep a list of symbols referenced from the command line */
  1256.  
  1257.   cl_refs_allocated = 10;
  1258.   cmdline_references =
  1259.     (struct glosym **) xmalloc (cl_refs_allocated
  1260.                   * sizeof(struct glosym *));
  1261.   *cmdline_references = 0;
  1262.  
  1263.   /* Completely decode ARGV.  */
  1264.  
  1265.   decode_command (argc, argv);
  1266.  
  1267.   /* Create the symbols `etext', `edata' and `end'.  */
  1268.  
  1269.   if (!relocatable_output)
  1270.     symtab_init ();
  1271.  
  1272.   /* Determine whether to count the header as part of
  1273.      the text size, and initialize the text size accordingly.
  1274.      This depends on the kind of system and on the output format selected.  */
  1275.  
  1276.   N_SET_MAGIC (outheader, magic);
  1277. #ifdef INITIALIZE_HEADER
  1278.   INITIALIZE_HEADER;
  1279. #endif
  1280.  
  1281.   text_size = sizeof (struct exec);
  1282. #ifdef COFF_ENCAPSULATE
  1283.   if (relocatable_output == 0)
  1284.     {
  1285.       need_coff_header = 1;
  1286.       /* set this flag now, since it will change the values of N_TXTOFF, etc */
  1287.       N_SET_FLAGS (outheader, N_FLAGS_COFF_ENCAPSULATE);
  1288.       text_size += sizeof (struct coffheader);
  1289.     }
  1290. #endif
  1291.  
  1292.   text_size -= N_TXTOFF (outheader);
  1293.  
  1294.   if (T_flag_specified)
  1295.       text_size = 0;    /* don't add sizeof(exec) at -T location */
  1296.  
  1297.   if (text_size < 0)
  1298.     text_size = 0;
  1299.   entry_offset = text_size;
  1300.  
  1301.   if (!T_flag_specified && !relocatable_output)
  1302.     text_start = N_TXTADDR (outheader);
  1303.  
  1304.   /* The text-start address is normally this far past a page boundary.  */
  1305.   text_start_alignment = text_start % page_size;
  1306.  
  1307.   /* Load symbols of all input files.
  1308.      Also search all libraries and decide which library members to load.  */
  1309.  
  1310.   load_symbols ();
  1311.  
  1312.   /* Compute where each file's sections go, and relocate symbols.  */
  1313.  
  1314.   digest_symbols ();
  1315.  
  1316.   /* Print error messages for any missing symbols, for any warning
  1317.      symbols, and possibly multiple definitions */
  1318.  
  1319.   do_warnings (stderr);
  1320.  
  1321.   /* Print a map, if requested.  */
  1322.  
  1323.   if (write_map) print_symbols (stdout);
  1324.  
  1325.   /* Write the output file.  */
  1326.  
  1327.   if (make_executable || force_executable)
  1328.     write_output ();
  1329.  
  1330.   exit (!make_executable);
  1331. }
  1332.  
  1333. void decode_option ();
  1334.  
  1335. /* Analyze a command line argument.
  1336.    Return 0 if the argument is a filename.
  1337.    Return 1 if the argument is a option complete in itself.
  1338.    Return 2 if the argument is a option which uses an argument.
  1339.  
  1340.    Thus, the value is the number of consecutive arguments
  1341.    that are part of options.  */
  1342.  
  1343. int
  1344. classify_arg (arg)
  1345.      register char *arg;
  1346. {
  1347.   if (*arg != '-') return 0;
  1348.   switch (arg[1])
  1349.     {
  1350.     case 'A':
  1351.     case 'D':
  1352.     case 'e':
  1353.     case 'L':
  1354.     case 'l':
  1355.     case 'o':
  1356.     case 'u':
  1357.     case 'V':
  1358.     case 'y':
  1359.     case 'Z':
  1360.       if (arg[2])
  1361.     return 1;
  1362.       return 2;
  1363.  
  1364.     case 'B':
  1365.       if (! strcmp (&arg[2], "static"))
  1366.     return 1;
  1367.  
  1368.     case 'T':
  1369.       if (arg[2] == 0)
  1370.     return 2;
  1371.       if (! strcmp (&arg[2], "text"))
  1372.     return 2;
  1373.       if (! strcmp (&arg[2], "data"))
  1374.     return 2;
  1375.       return 1;
  1376.  
  1377. #if TARGET==TARGET_SEQUENT      
  1378.       /* k == Symmetry standalone,
  1379.        * p == don't align text/data boundary (for 8K disk bootstraps).
  1380.        */
  1381.    case 'k':
  1382.    case 'p':
  1383.        return 1;
  1384. #endif       
  1385.     }
  1386.  
  1387.   return 1;
  1388. }
  1389.  
  1390. /* Process the command arguments,
  1391.    setting up file_table with an entry for each input file,
  1392.    and setting variables according to the options.  */
  1393.  
  1394. void
  1395. decode_command (argc, argv)
  1396.      char **argv;
  1397.      int argc;
  1398. {
  1399.   int optc, longind;
  1400.   register struct file_entry *p;
  1401.  
  1402.   number_of_files = 0;
  1403.   output_filename = "a.out";
  1404.  
  1405.   n_search_dirs = 0;
  1406.   search_dirs = (char **) xmalloc (sizeof (char *));
  1407.  
  1408.   /* First compute number_of_files so we know how long to make file_table.  */
  1409.   /* Also process most options completely.  */
  1410.  
  1411.   for (i = 1; i < argc; i++)
  1412.     {
  1413.       register int code = classify_arg (argv[i]);
  1414.       if (code)
  1415.     {
  1416.       if (i + code > argc)
  1417.         fatal ("no argument following %s\n", argv[i]);
  1418.  
  1419.       decode_option (argv[i], argv[i+1]);
  1420.  
  1421.       if (argv[i][1] == 'l' || argv[i][1] == 'A')
  1422.         number_of_files++;
  1423.  
  1424.       i += code - 1;
  1425.     }
  1426.       else
  1427.     number_of_files++;
  1428.     }
  1429.  
  1430.   if (!number_of_files)
  1431.     fatal ("no input files", 0);
  1432.  
  1433.   p = file_table
  1434.     = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
  1435.   bzero (p, number_of_files * sizeof (struct file_entry));
  1436.  
  1437.   /* Now scan again and fill in file_table.  */
  1438.   /* All options except -A and -l are ignored here.  */
  1439.  
  1440.   for (i = 1; i < argc; i++)
  1441.     {
  1442.       register int code = classify_arg (argv[i]);
  1443.  
  1444.       if (code)
  1445.     {
  1446.       char *string;
  1447.       if (code == 2)
  1448.         string = argv[i+1];
  1449.       else
  1450.         string = &argv[i][2];
  1451.  
  1452.       if (argv[i][1] == 'A')
  1453.         {
  1454.           if (p != file_table)
  1455.         fatal ("-A specified before an input file other than the first");
  1456.  
  1457.           p->filename = string;
  1458.           p->local_sym_name = string;
  1459.           p->just_syms_flag = 1;
  1460.           p++;
  1461.         }
  1462.       if (argv[i][1] == 'l')
  1463.         {
  1464.           p->filename = concat ("lib", string, ".a");
  1465.           p->local_sym_name = concat ("-l", string, "");
  1466.           p->search_dirs_flag = 1;
  1467.           p++;
  1468.         }
  1469.       i += code - 1;
  1470.     }
  1471.       else
  1472.     {
  1473.       p->filename = argv[i];
  1474.       p->local_sym_name = argv[i];
  1475.       p++;
  1476.     }
  1477.     }
  1478.  
  1479.   /* Now check some option settings for consistency.  */
  1480.  
  1481. #ifndef sprite
  1482. #ifdef NMAGIC
  1483.   if ((magic == ZMAGIC || magic == NMAGIC)
  1484. #else
  1485. #ifdef SMAGIC
  1486.     if ((magic == SMAGIC || magic == ZMAGIC)
  1487. #else
  1488.     if ((magic == ZMAGIC)
  1489. #endif /* SMAGIC */
  1490. #endif
  1491.       && (text_start - text_start_alignment) & (page_size - 1))
  1492.     fatal ("-T argument not multiple of page size, with sharable output", 0);
  1493. #endif
  1494.  
  1495.   /* Append the standard search directories to the user-specified ones.  */
  1496.   {
  1497.     int n = sizeof standard_search_dirs / sizeof standard_search_dirs[0];
  1498.     n_search_dirs += n;
  1499.     search_dirs
  1500.       = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1501.     bcopy (standard_search_dirs, &search_dirs[n_search_dirs - n],
  1502.        n * sizeof (char *));
  1503.   }
  1504. }
  1505.  
  1506.  
  1507. void
  1508. add_cmdline_ref (sp)
  1509.      struct glosym *sp;
  1510. {
  1511.   struct glosym **ptr;
  1512.  
  1513.   for (ptr = cmdline_references;
  1514.        ptr < cmdline_references + cl_refs_allocated && *ptr;
  1515.        ptr++)
  1516.     ;
  1517.  
  1518.   if (ptr >= cmdline_references + cl_refs_allocated - 1)
  1519.     {
  1520.       int diff = ptr - cmdline_references;
  1521.  
  1522.       cl_refs_allocated *= 2;
  1523.       cmdline_references = (struct glosym **)
  1524.     xrealloc (cmdline_references,
  1525.          cl_refs_allocated * sizeof (struct glosym *));
  1526.       ptr = cmdline_references + diff;
  1527.     }
  1528.  
  1529.   *ptr++ = sp;
  1530.   *ptr = (struct glosym *) 0;
  1531. }
  1532.  
  1533. int
  1534. set_element_prefixed_p (name)
  1535.      char *name;
  1536. {
  1537.   struct string_list_element *p;
  1538.   int i;
  1539.  
  1540.   for (p = set_element_prefixes; p; p = p->next)
  1541.     {
  1542.       for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++)
  1543.     ;
  1544.  
  1545.       if (p->str[i] == '\0')
  1546.     return 1;
  1547.     }
  1548.   return 0;
  1549. }
  1550.  
  1551. int parse ();
  1552.  
  1553. /* Record an option and arrange to act on it later.
  1554.    ARG should be the following command argument,
  1555.    which may or may not be used by this option.
  1556.  
  1557.    The `l' and `A' options are ignored here since they actually
  1558.    specify input files.  */
  1559.  
  1560. void
  1561. decode_option (swt, arg)
  1562.      register char *swt, *arg;
  1563. {
  1564.   /* We get Bstatic from gcc on suns.  */
  1565.   if (! strcmp (swt + 1, "Bstatic"))
  1566.     return;
  1567.   if (! strcmp (swt + 1, "Ttext"))
  1568.     {
  1569. #ifdef sprite 
  1570.       magic = OMAGIC;
  1571. #endif
  1572.       text_start = parse (arg, "%x", "invalid argument to -Ttext");
  1573.       T_flag_specified = 1;
  1574.       return;
  1575.     }
  1576.   if (! strcmp (swt + 1, "Tdata"))
  1577.     {
  1578.       data_start = parse (arg, "%x", "invalid argument to -Tdata");
  1579.       Tdata_flag_specified = 1;
  1580.       return;
  1581.     }
  1582.   if (! strcmp (swt + 1, "noinhibit-exec"))
  1583.     {
  1584.       force_executable = 1;
  1585.       return;
  1586.     }
  1587.  
  1588.   if (swt[2] != 0)
  1589.     arg = &swt[2];
  1590.  
  1591.   switch (swt[1])
  1592.     {
  1593.     case 'A':
  1594.       return;
  1595.  
  1596.     case 'D':
  1597.       specified_data_size = parse (arg, "%x", "invalid argument to -D");
  1598.       return;
  1599.  
  1600.     case 'd':
  1601.       force_common_definition = 1;
  1602.       return;
  1603.  
  1604.     case 'e':
  1605.       entry_symbol = getsym (arg);
  1606.       if (!entry_symbol->defined && !entry_symbol->referenced)
  1607.     undefined_global_sym_count++;
  1608.       entry_symbol->referenced = 1;
  1609.       add_cmdline_ref (entry_symbol);
  1610.       return;
  1611.  
  1612. #if TARGET==TARGET_SEQUENT
  1613.     case 'k':
  1614. #ifdef SMAGIC
  1615.       magic = SMAGIC;
  1616. #else
  1617.       fatal("No SMAGIC defined for -k");
  1618. #endif
  1619.       return;
  1620. #endif
  1621.  
  1622.     case 'l':
  1623. #ifndef NO_C_PLUS_PLUS
  1624.       /* If linking with libg++, use the C++ demangler. */
  1625.       if (arg != NULL && strcmp (arg, "g++") == 0)
  1626.       demangler = cplus_demangle;
  1627. #endif /* NO_C_PLUS_PLUS */
  1628.       return;
  1629.  
  1630.     case 'L':
  1631.       n_search_dirs++;
  1632.       search_dirs
  1633.     = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1634.       search_dirs[n_search_dirs - 1] = arg;
  1635.       return;
  1636.  
  1637.     case 'M':
  1638.       write_map = 1;
  1639.       return;
  1640.  
  1641.     case 'N':
  1642.       magic = OMAGIC;
  1643.       return;
  1644.  
  1645. #ifdef NMAGIC
  1646.     case 'n':
  1647.       magic = NMAGIC;
  1648.       return;
  1649. #endif
  1650.  
  1651.     case 'o':
  1652.       output_filename = arg;
  1653.       return;
  1654.  
  1655.     case 'r':
  1656.       relocatable_output = 1;
  1657.       magic = OMAGIC;
  1658.       text_start = 0;
  1659.       return;
  1660.  
  1661.     case 'S':
  1662.       strip_symbols = STRIP_DEBUGGER;
  1663.       return;
  1664.  
  1665.     case 's':
  1666.       strip_symbols = STRIP_ALL;
  1667.       return;
  1668.  
  1669.     case 'T':
  1670. #ifdef sprite
  1671.       magic = OMAGIC;
  1672. #endif      
  1673.       text_start = parse (arg, "%x", "invalid argument to -T");
  1674.       T_flag_specified = 1;
  1675.       return;
  1676.  
  1677.     case 't':
  1678.       trace_files = 1;
  1679.       return;
  1680.  
  1681.     case 'u':
  1682.       {
  1683.     register symbol *sp = getsym (arg);
  1684.     if (!sp->defined && !sp->referenced)
  1685.       undefined_global_sym_count++;
  1686.     sp->referenced = 1;
  1687.     add_cmdline_ref (sp);
  1688.       }
  1689.       return;
  1690.  
  1691.     case 'V':
  1692.       {
  1693.     struct string_list_element *new
  1694.       = (struct string_list_element *)
  1695.         xmalloc (sizeof (struct string_list_element));
  1696.  
  1697.     new->str = arg;
  1698.     new->next = set_element_prefixes;
  1699.     set_element_prefixes = new;
  1700.     return;
  1701.       }
  1702.  
  1703.     case 'X':
  1704.       discard_locals = DISCARD_L;
  1705.       return;
  1706.  
  1707.     case 'x':
  1708.       discard_locals = DISCARD_ALL;
  1709.       return;
  1710.  
  1711.     case 'y':
  1712.       {
  1713.     register symbol *sp = getsym (&swt[2]);
  1714.     sp->trace = 1;
  1715.       }
  1716.       return;
  1717.  
  1718.     case 'z':
  1719.       magic = ZMAGIC;
  1720.       return;
  1721.  
  1722.     case 'Z':
  1723.       data_gap = parse (arg, "%x", "invalid argument to -Z");
  1724.       if (data_gap % page_size)
  1725.       fatal("-Z argument not a multiple of page size", 0);
  1726.       Z_flag_specified = 1;
  1727.       return;
  1728.  
  1729.     default:
  1730.       fatal ("invalid command option `%s'", swt);
  1731.     }
  1732. }
  1733.  
  1734. /** Convenient functions for operating on one or all files being */
  1735.  /** loaded.  */
  1736. void print_file_name ();
  1737.  
  1738. /* Call FUNCTION on each input file entry.
  1739.    Do not call for entries for libraries;
  1740.    instead, call once for each library member that is being loaded.
  1741.  
  1742.    FUNCTION receives two arguments: the entry, and ARG.  */
  1743.  
  1744. void
  1745. each_file (function, arg)
  1746.      register void (*function)();
  1747.      register int arg;
  1748. {
  1749.   register int i;
  1750.  
  1751.   for (i = 0; i < number_of_files; i++)
  1752.     {
  1753.       register struct file_entry *entry = &file_table[i];
  1754.       if (entry->library_flag)
  1755.         {
  1756.       register struct file_entry *subentry = entry->subfiles;
  1757.       for (; subentry; subentry = subentry->chain)
  1758.         (*function) (subentry, arg);
  1759.     }
  1760.       else
  1761.     (*function) (entry, arg);
  1762.     }
  1763. }
  1764.  
  1765. /* Call FUNCTION on each input file entry until it returns a non-zero
  1766.    value.  Return this value.
  1767.    Do not call for entries for libraries;
  1768.    instead, call once for each library member that is being loaded.
  1769.  
  1770.    FUNCTION receives two arguments: the entry, and ARG.  It must be a
  1771.    function returning unsigned long (though this can probably be fudged). */
  1772. #if 0
  1773. unsigned long
  1774. check_each_file (function, arg)
  1775.      register unsigned long (*function)();
  1776.      register int arg;
  1777. {
  1778.   register int i;
  1779.   register unsigned long return_val;
  1780.  
  1781.   for (i = 0; i < number_of_files; i++)
  1782.     {
  1783.       register struct file_entry *entry = &file_table[i];
  1784.       if (entry->library_flag)
  1785.         {
  1786.       register struct file_entry *subentry = entry->subfiles;
  1787.       for (; subentry; subentry = subentry->chain)
  1788.         if (return_val = (*function) (subentry, arg))
  1789.           return return_val;
  1790.     }
  1791.       else
  1792.     if (return_val = (*function) (entry, arg))
  1793.       return return_val;
  1794.     }
  1795.   return 0;
  1796. }
  1797. #endif
  1798.  
  1799. /* Like `each_file' but ignore files that were just for symbol definitions.  */
  1800.  
  1801. void
  1802. each_full_file (function, arg)
  1803.      register void (*function)();
  1804.      register int arg;
  1805. {
  1806.   register int i;
  1807.  
  1808.   for (i = 0; i < number_of_files; i++)
  1809.     {
  1810.       register struct file_entry *entry = &file_table[i];
  1811.       if (entry->just_syms_flag)
  1812.     continue;
  1813.       if (entry->library_flag)
  1814.         {
  1815.       register struct file_entry *subentry = entry->subfiles;
  1816.       for (; subentry; subentry = subentry->chain)
  1817.         (*function) (subentry, arg);
  1818.     }
  1819.       else
  1820.     (*function) (entry, arg);
  1821.     }
  1822. }
  1823.  
  1824. /* Close the input file that is now open.  */
  1825.  
  1826. void
  1827. file_close ()
  1828. {
  1829.   close (input_desc);
  1830.   input_desc = 0;
  1831.   input_file = 0;
  1832. }
  1833.  
  1834. /* Open the input file specified by 'entry', and return a descriptor.
  1835.    The open file is remembered; if the same file is opened twice in a row,
  1836.    a new open is not actually done.  */
  1837.  
  1838. int
  1839. file_open (entry)
  1840.      register struct file_entry *entry;
  1841. {
  1842.   register int desc;
  1843.  
  1844.   if (entry->superfile)
  1845.     return file_open (entry->superfile);
  1846.  
  1847.   if (entry == input_file)
  1848.     return input_desc;
  1849.  
  1850.   if (input_file) file_close ();
  1851.  
  1852.   if (entry->search_dirs_flag)
  1853.     {
  1854.       int i;
  1855.  
  1856.       for (i = 0; i < n_search_dirs; i++)
  1857.     {
  1858.       register char *string
  1859.         = concat (search_dirs[i], "/", entry->filename);
  1860.       desc = open (string, O_RDONLY, 0);
  1861.       if (desc > 0)
  1862.         {
  1863.           entry->filename = string;
  1864.           entry->search_dirs_flag = 0;
  1865.           break;
  1866.         }
  1867.       free (string);
  1868.     }
  1869.     }
  1870.   else
  1871.     desc = open (entry->filename, O_RDONLY, 0);
  1872.  
  1873.   if (desc > 0)
  1874.     {
  1875.       input_file = entry;
  1876.       input_desc = desc;
  1877.       return desc;
  1878.     }
  1879.  
  1880.   perror_file (entry);
  1881.   /* NOTREACHED */
  1882. }
  1883.  
  1884. /* Print the filename of ENTRY on OUTFILE (a stdio stream),
  1885.    and then a newline.  */
  1886.  
  1887. void
  1888. prline_file_name (entry, outfile)
  1889.      struct file_entry *entry;
  1890.      FILE *outfile;
  1891. {
  1892.   print_file_name (entry, outfile);
  1893.   fprintf (outfile, "\n");
  1894. }
  1895.  
  1896. /* Print the filename of ENTRY on OUTFILE (a stdio stream).  */
  1897.  
  1898. void
  1899. print_file_name (entry, outfile)
  1900.      struct file_entry *entry;
  1901.      FILE *outfile;
  1902. {
  1903.   if (entry->superfile)
  1904.     {
  1905.       print_file_name (entry->superfile, outfile);
  1906.       fprintf (outfile, "(%s)", entry->filename);
  1907.     }
  1908.   else
  1909.     fprintf (outfile, "%s", entry->filename);
  1910. }
  1911.  
  1912. /* Return the filename of entry as a string (malloc'd for the purpose) */
  1913.  
  1914. char *
  1915. get_file_name (entry)
  1916.      struct file_entry *entry;
  1917. {
  1918.   char *result, *supfile;
  1919.   if (entry->superfile)
  1920.     {
  1921.       supfile = get_file_name (entry->superfile);
  1922.       result = (char *) xmalloc (strlen (supfile)
  1923.                  + strlen (entry->filename) + 3);
  1924.       sprintf (result, "%s(%s)", supfile, entry->filename);
  1925.       free (supfile);
  1926.     }
  1927.   else
  1928.     {
  1929.       result = (char *) xmalloc (strlen (entry->filename) + 1);
  1930.       strcpy (result, entry->filename);
  1931.     }
  1932.   return result;
  1933. }
  1934.  
  1935. /* Medium-level input routines for rel files.  */
  1936.  
  1937. /* Determine whether the given ENTRY is an archive, a BSD a.out file,
  1938.    a Mach-O file, or whatever.  DESC is the descriptor on which the
  1939.    file is open.  */
  1940. void
  1941. deduce_file_type(desc, entry)
  1942.      int desc;
  1943.      struct file_entry *entry;
  1944. {
  1945.   int len;
  1946.  
  1947.   {
  1948.     char magic[SARMAG];
  1949.     
  1950.     lseek (desc, entry->starting_offset, 0);
  1951.     len = read (desc, magic, SARMAG);
  1952.     if (len == SARMAG && !strncmp(magic, ARMAG, SARMAG))
  1953.       {
  1954.     entry->file_type = IS_ARCHIVE;
  1955.     return;
  1956.       }
  1957.   }
  1958.  
  1959. #ifdef A_OUT
  1960.   {
  1961.     struct exec hdr;
  1962.  
  1963.     lseek (desc, entry->starting_offset, 0);
  1964. #ifdef COFF_ENCAPSULATE
  1965.     if (entry->just_syms_flag)
  1966.       /* Since a file given with -A will have a coff header, unlike normal
  1967.     input files, we need to skip over it.  */
  1968.       lseek (desc, sizeof (coffheader), SEEK_CUR);
  1969. #endif
  1970.     len = read (desc, (char *) &hdr, sizeof (struct exec));
  1971.     if (len == sizeof (struct exec) && !N_BADMAG (hdr))
  1972.       {
  1973.     entry->file_type = IS_A_OUT;
  1974.     return;
  1975.       }
  1976.   }
  1977. #endif
  1978.  
  1979. #ifdef MACH_O
  1980.   {
  1981.     struct mach_header hdr;
  1982.  
  1983.     lseek (desc, entry->starting_offset, 0);
  1984.     len = read (desc, (char *) &hdr, sizeof (struct mach_header));
  1985.     if (len == sizeof (struct mach_header) && hdr.magic == MH_MAGIC)
  1986.       {
  1987.     entry->file_type = IS_MACH_O;
  1988.     return;
  1989.       }
  1990.   }
  1991. #endif
  1992.  
  1993.   fatal_with_file ("malformed input file (not rel or archive) ", entry);
  1994. }
  1995.  
  1996. #ifdef A_OUT
  1997. /* Read an a.out file's header and set up the fields of
  1998.    the ENTRY accordingly.  DESC is the descriptor on which
  1999.    the file is open.  */
  2000. void
  2001. read_a_out_header (desc, entry)
  2002.      int desc;
  2003.      struct file_entry *entry;
  2004. {
  2005.   register int len;
  2006.   struct exec hdr;
  2007.   struct stat st;
  2008.  
  2009.   lseek (desc, entry->starting_offset, 0);
  2010.  
  2011. #ifdef COFF_ENCAPSULATE
  2012.   if (entry->just_syms_flag)
  2013.     /* Since a file given with -A will have a coff header, unlike normal
  2014.        input files, we need to skip over it.  */
  2015.     lseek (desc, sizeof (coffheader), SEEK_CUR);
  2016. #endif
  2017.  
  2018.   read (desc, (char *) &hdr, sizeof (struct exec));
  2019.  
  2020. #ifdef READ_HEADER_HOOK
  2021.   READ_HEADER_HOOK(hdr.a_machtype);
  2022. #endif
  2023.  
  2024.   if (entry->just_syms_flag)
  2025.     entry->orig_text_address = N_TXTADDR(hdr);
  2026.   else
  2027.     entry->orig_text_address = 0;
  2028.   entry->text_size = hdr.a_text;
  2029.   entry->text_offset = N_TXTOFF(hdr);
  2030.  
  2031.   entry->text_reloc_size = hdr.a_trsize;
  2032. #ifdef N_TRELOFF
  2033.   entry->text_reloc_offset = N_TRELOFF(hdr);
  2034. #else
  2035. #ifdef N_DATOFF
  2036.   entry->text_reloc_offset = N_DATOFF(hdr) + hdr.a_data;
  2037. #else
  2038.   entry->text_reloc_offset = N_TXTOFF(hdr) + hdr.a_text + hdr.a_data;
  2039. #endif
  2040. #endif
  2041.  
  2042.   if (entry->just_syms_flag)
  2043.     entry->orig_data_address = N_DATADDR(hdr);
  2044.   else
  2045.     entry->orig_data_address = entry->text_size;
  2046.   entry->data_size = hdr.a_data;
  2047. #ifdef N_DATOFF
  2048.   entry->data_offset = N_DATOFF(hdr);
  2049. #else
  2050.   entry->data_offset = N_TXTOFF(hdr) + hdr.a_text;
  2051. #endif
  2052.  
  2053.   entry->data_reloc_size = hdr.a_drsize;
  2054. #ifdef N_DRELOFF
  2055.   entry->data_reloc_offset = N_DRELOFF(hdr);
  2056. #else
  2057.   entry->data_reloc_offset = entry->text_reloc_offset + entry->text_reloc_size;
  2058. #endif
  2059.  
  2060. #ifdef N_BSSADDR
  2061.   if (entry->just_syms_flag)
  2062.     entry->orig_bss_address = N_BSSADDR(hdr);
  2063.   else
  2064. #endif
  2065.   entry->orig_bss_address = entry->orig_data_address + entry->data_size;
  2066.   entry->bss_size = hdr.a_bss;
  2067.  
  2068.   entry->syms_size = hdr.a_syms;
  2069.   entry->syms_offset = N_SYMOFF(hdr);
  2070.   entry->strs_offset = N_STROFF(hdr);
  2071.   lseek(desc, entry->starting_offset + entry->strs_offset, 0);
  2072.   if (read(desc, (char *) &entry->strs_size, sizeof (unsigned long int))
  2073.       != sizeof (unsigned long int))
  2074.     fatal_with_file ("failure reading string table size of ", entry);
  2075.  
  2076.   if (!entry->superfile)
  2077.     {
  2078.       fstat(desc, &st);
  2079.       if (st.st_size > entry->strs_offset + entry->strs_size)
  2080.     {
  2081.       entry->symseg_size = st.st_size - (entry->strs_offset + entry->strs_size);
  2082.       entry->symseg_offset = entry->strs_offset + entry->strs_size;
  2083.     }
  2084.     }
  2085.   else
  2086.     if (entry->total_size > entry->strs_offset + entry->strs_size)
  2087.       {
  2088.     entry->symseg_size = entry->total_size - (entry->strs_offset + entry->strs_size);
  2089.     entry->symseg_offset = entry->strs_offset + entry->strs_size;
  2090.       }
  2091. }
  2092. #endif
  2093.  
  2094. #ifdef MACH_O
  2095. /* Read a Mach-O file's header.  DESC is the descriptor on which the
  2096.    file is open, and ENTRY is the file's entry.  */
  2097. void
  2098. read_mach_o_header (desc, entry)
  2099.      int desc;
  2100.      struct file_entry *entry;
  2101. {
  2102.   struct mach_header mach_header;
  2103.   char *hdrbuf;
  2104.   struct load_command *load_command;
  2105.   struct segment_command *segment_command;
  2106.   struct section *section;
  2107.   struct symtab_command *symtab_command;
  2108. #ifdef LC_SYMSEG
  2109.   struct symseg_command *symseg_command;
  2110. #endif;
  2111.   int ordinal;
  2112.   int symtab_seen, symseg_seen;
  2113.   int len, cmd, seg;
  2114.  
  2115.   entry->text_ordinal = entry->data_ordinal = entry->bss_ordinal = 0;
  2116.   symtab_seen = symseg_seen = 0;
  2117.   ordinal = 1;
  2118.  
  2119.   lseek (desc, entry->starting_offset, 0);
  2120.   len = read (desc, (char *) &mach_header, sizeof (struct mach_header));
  2121.   if (len != sizeof (struct mach_header))
  2122.     fatal_with_file ("failure reading Mach-O header of ", entry);
  2123.   if (mach_header.filetype != MH_OBJECT && mach_header.filetype != MH_EXECUTE)
  2124.     fatal_with_file ("unsupported Mach-O file type (not MH_OBJECT or MH_EXECUTE) in ", entry);
  2125.   hdrbuf = xmalloc (mach_header.sizeofcmds);
  2126.   len = read (desc, hdrbuf, mach_header.sizeofcmds);
  2127.   if (len != mach_header.sizeofcmds)
  2128.     fatal_with_file ("failure reading Mach-O load commands of ", entry);
  2129.   load_command = (struct load_command *) hdrbuf;
  2130.   for (cmd = 0; cmd < mach_header.ncmds; ++cmd)
  2131.     {
  2132.       switch (load_command->cmd)
  2133.     {
  2134.     case LC_SEGMENT:
  2135.       segment_command = (struct segment_command *) load_command;
  2136.       section = (struct section *) ((char *) (segment_command + 1));
  2137.       for (seg = 0; seg < segment_command->nsects; ++seg, ++section, ++ordinal)
  2138.         {
  2139.           if (!strncmp(SECT_TEXT, section->sectname, sizeof section->sectname))
  2140.         if (entry->text_ordinal)
  2141.           fatal_with_file ("more than one __text section in ", entry);
  2142.         else
  2143.           {
  2144.             entry->text_ordinal = ordinal;
  2145.             entry->orig_text_address = section->addr;
  2146.             entry->text_size = section->size;
  2147.             entry->text_offset = section->offset;
  2148.             entry->text_reloc_size = section->nreloc * sizeof (struct relocation_info);
  2149.             entry->text_reloc_offset = section->reloff;
  2150.           }
  2151.           else if (!strncmp(SECT_DATA, section->sectname, sizeof section->sectname))
  2152.         if (entry->data_ordinal)
  2153.           fatal_with_file ("more than one __data section in ", entry);
  2154.         else
  2155.           {
  2156.             entry->data_ordinal = ordinal;
  2157.             entry->orig_data_address = section->addr;
  2158.             entry->data_size = section->size;
  2159.             entry->data_offset = section->offset;
  2160.             entry->data_reloc_size = section->nreloc * sizeof (struct relocation_info);
  2161.             entry->data_reloc_offset = section->reloff;
  2162.           }
  2163.           else if (!strncmp(SECT_BSS, section->sectname, sizeof section->sectname))
  2164.         if (entry->bss_ordinal)
  2165.           fatal_with_file ("more than one __bss section in ", entry);
  2166.         else
  2167.           {
  2168.             entry->bss_ordinal = ordinal;
  2169.             entry->orig_bss_address = section->addr;
  2170.             entry->bss_size = section->size;
  2171.           }
  2172.           else
  2173.         if (section->size != 0)
  2174.           fprintf (stderr, "%s: warning: unknown section `%.*s' in %s\n",
  2175.                progname, sizeof section->sectname, section->sectname,
  2176.                entry->filename);
  2177.         }
  2178.       break;
  2179.     case LC_SYMTAB:
  2180.       if (symtab_seen)
  2181.           fatal_with_file ("more than one LC_SYMTAB in ", entry);
  2182.       else
  2183.         {
  2184.           symtab_seen = 1;
  2185.           symtab_command = (struct symtab_command *) load_command;
  2186.           entry->syms_size = symtab_command->nsyms * sizeof (struct nlist);
  2187.           entry->syms_offset = symtab_command->symoff;
  2188.           entry->strs_size = symtab_command->strsize;
  2189.           entry->strs_offset = symtab_command->stroff;
  2190.         }
  2191.       break;
  2192. #ifdef LC_SYMSEG
  2193.     case LC_SYMSEG:
  2194.       if (symseg_seen)
  2195.         fatal_with_file ("more than one LC_SYMSEG in ", entry);
  2196.       else
  2197.         {
  2198.           symseg_seen = 1;
  2199.           symseg_command = (struct symseg_command *) load_command;
  2200.           entry->symseg_size = symseg_command->size;
  2201.           entry->symseg_offset = symseg_command->offset;
  2202.         }
  2203.       break;
  2204. #endif
  2205.     }
  2206.       load_command = (struct load_command *)
  2207.     ((char *) load_command + load_command->cmdsize);
  2208.     }
  2209.  
  2210.   free (hdrbuf);
  2211.  
  2212.   if (!symtab_seen)
  2213.     fprintf (stderr, "%s: no symbol table in %s\n", progname, entry->filename);
  2214. }
  2215. #endif
  2216.  
  2217. /* Read a file's header info into the proper place in the file_entry.
  2218.    DESC is the descriptor on which the file is open.
  2219.    ENTRY is the file's entry.
  2220.    Switch in the file_type to determine the appropriate actual
  2221.    header reading routine to call.  */
  2222.  
  2223. void
  2224. read_header (desc, entry)
  2225.      int desc;
  2226.      register struct file_entry *entry;
  2227. {
  2228.   register int len;
  2229.   struct exec *loc = (struct exec *) &entry->header;
  2230.  
  2231.   lseek (desc, entry->starting_offset, 0);
  2232.   len = read (desc, loc, sizeof (struct exec));
  2233.   if (len != sizeof (struct exec))
  2234.     fatal_with_file ("failure reading header of ", entry);
  2235. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2236.   fix_exec_header_byte_order(loc);
  2237. #endif
  2238.   if (N_BADMAG (*loc))
  2239.     fatal_with_file ("bad magic number in ", entry);
  2240.  
  2241.   entry->header_read_flag = 1;
  2242. }
  2243.  
  2244. /* Read the symbols of file ENTRY into core.
  2245.    Assume it is already open, on descriptor DESC.
  2246.    Also read the length of the string table, which follows the symbol table,
  2247.    but don't read the contents of the string table.  */
  2248.  
  2249. void
  2250. read_entry_symbols (desc, entry)
  2251.      struct file_entry *entry;
  2252.      int desc;
  2253. {
  2254.   int str_size;
  2255.  
  2256.   if (!entry->header_read_flag)
  2257.     read_header (desc, entry);
  2258.  
  2259.   entry->symbols = (struct nlist *) xmalloc (entry->header.a_syms);
  2260.  
  2261.   lseek (desc, N_SYMOFF (entry->header) + entry->starting_offset, 0);
  2262.   if (entry->header.a_syms != read (desc, entry->symbols, entry->header.a_syms))
  2263.     fatal_with_file ("premature end of file in symbols of ", entry);
  2264. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2265.   fix_symbol_byte_order(entry->symbols, entry->header.a_syms);
  2266. #endif
  2267.   lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  2268.   if (sizeof str_size != read (desc, &str_size, sizeof str_size))
  2269.     fatal_with_file ("bad string table size in ", entry);
  2270. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2271.   fix_byte_order(&str_size, sizeof(str_size));
  2272. #endif
  2273.   entry->string_size = str_size;
  2274. }
  2275.  
  2276. /* Read the string table of file ENTRY into core.
  2277.    Assume it is already open, on descriptor DESC.
  2278.    Also record whether a GDB symbol segment follows the string table.  */
  2279.  
  2280. void
  2281. read_entry_strings (desc, entry)
  2282.      struct file_entry *entry;
  2283.      int desc;
  2284. {
  2285.   int buffer;
  2286.  
  2287.   if (!entry->header_read_flag)
  2288.     read_header (desc, entry);
  2289.  
  2290.   lseek (desc, entry->strs_offset + entry->starting_offset, 0);
  2291.   if (entry->strs_size != read (desc, entry->strings, entry->strs_size))
  2292.     fatal_with_file ("premature end of file in strings of ", entry);
  2293. }
  2294.  
  2295. /* Read in the symbols of all input files.  */
  2296.  
  2297. void read_file_symbols (), read_entry_symbols (), read_entry_strings ();
  2298. void enter_file_symbols (), enter_global_ref (), search_library ();
  2299.  
  2300. void
  2301. load_symbols ()
  2302. {
  2303.   register int i;
  2304.  
  2305.   if (trace_files) fprintf (stderr, "Loading symbols:\n\n");
  2306.  
  2307.   for (i = 0; i < number_of_files; i++)
  2308.     {
  2309.       register struct file_entry *entry = &file_table[i];
  2310.       read_file_symbols (entry);
  2311.     }
  2312.  
  2313.   if (trace_files) fprintf (stderr, "\n");
  2314. }
  2315.  
  2316. /* If ENTRY is a rel file, read its symbol and string sections into core.
  2317.    If it is a library, search it and load the appropriate members
  2318.    (which means calling this function recursively on those members).  */
  2319.  
  2320. void
  2321. read_file_symbols (entry)
  2322.      register struct file_entry *entry;
  2323. {
  2324.   register int desc;
  2325.   register int len;
  2326.   struct exec hdr;
  2327.  
  2328.   desc = file_open (entry);
  2329.  
  2330.   len = read (desc, &hdr, sizeof hdr);
  2331.   if (len != sizeof hdr)
  2332.     fatal_with_file ("failure reading header of ", entry);
  2333. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2334.   fix_exec_header_byte_order(&hdr);
  2335. #endif
  2336.   if (!N_BADMAG (hdr))
  2337.     {
  2338.       read_entry_symbols (desc, entry);
  2339.       entry->strings = (char *) alloca (entry->string_size);
  2340.       read_entry_strings (desc, entry);
  2341.       enter_file_symbols (entry);
  2342.       entry->strings = 0;
  2343.     }
  2344.   else
  2345.     {
  2346.       char armag[SARMAG];
  2347.  
  2348.       lseek (desc, 0, 0);
  2349.       if (SARMAG != read (desc, armag, SARMAG) || strncmp (armag, ARMAG, SARMAG))
  2350.     fatal_with_file ("malformed input file (not rel or archive) ", entry);
  2351.       entry->library_flag = 1;
  2352.       search_library (desc, entry);
  2353.     }
  2354.  
  2355.   file_close ();
  2356. }
  2357.  
  2358. /* Enter the external symbol defs and refs of ENTRY in the hash table.  */
  2359.  
  2360. void
  2361. enter_file_symbols (entry)
  2362.      struct file_entry *entry;
  2363. {
  2364.   register struct nlist
  2365.     *p,
  2366.     *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  2367.  
  2368.   if (trace_files) prline_file_name (entry, stderr);
  2369.  
  2370.   for (p = entry->symbols; p < end; p++)
  2371.     {
  2372.       if (p->n_type == (N_SETV | N_EXT)) continue;
  2373.       if (set_element_prefixes
  2374.       && set_element_prefixed_p (p->n_un.n_strx + entry->strings))
  2375.     p->n_type += (N_SETA - N_ABS);
  2376.       if (SET_ELEMENT_P (p->n_type))
  2377.     {
  2378.       set_symbol_count++;
  2379.       if (output_style != OUTPUT_RELOCATABLE)
  2380.         enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2381.     }
  2382.       else if (p->n_type == N_WARNING)
  2383.     {
  2384.       char *name = p->n_un.n_strx + entry->strings;
  2385.  
  2386.       /* Grab the next entry.  */
  2387.       p++;
  2388.       if (p->n_type != (N_UNDF | N_EXT))
  2389.         {
  2390.           fprintf (stderr, "%s: Warning symbol found in %s without external reference following.\n",
  2391.                progname, entry->filename);
  2392.           make_executable = 0;
  2393.           p--;        /* Process normally.  */
  2394.         }
  2395.       else
  2396.         {
  2397.           symbol *sp;
  2398.           char *sname = p->n_un.n_strx + entry->strings;
  2399.           /* Deal with the warning symbol.  */
  2400.           enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2401.           sp = getsym (sname);
  2402.           sp->warning = (char *) xmalloc (strlen(name) + 1);
  2403.           strcpy (sp->warning, name);
  2404.           warning_count++;
  2405.         }
  2406.     }
  2407.       else if (p->n_type & N_EXT)
  2408.     enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2409.       else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
  2410.     {
  2411.       if ((p->n_un.n_strx + entry->strings)[0] != LPREFIX)
  2412.         non_L_local_sym_count++;
  2413.       local_sym_count++;
  2414.     }
  2415.       else debugger_sym_count++;
  2416.     }
  2417.  
  2418.    /* Count one for the local symbol that we generate,
  2419.       whose name is the file's name (usually) and whose address
  2420.       is the start of the file's text.  */
  2421.  
  2422.   local_sym_count++;
  2423.   non_L_local_sym_count++;
  2424. }
  2425.  
  2426. /* Enter one global symbol in the hash table.
  2427.    NLIST_P points to the `struct nlist' read from the file
  2428.    that describes the global symbol.  NAME is the symbol's name.
  2429.    ENTRY is the file entry for the file the symbol comes from.
  2430.  
  2431.    The `struct nlist' is modified by placing it on a chain of
  2432.    all such structs that refer to the same global symbol.
  2433.    This chain starts in the `refs' field of the symbol table entry
  2434.    and is chained through the `n_name'.  */
  2435. void
  2436. enter_global_ref (nlist_p, name, entry)
  2437.      register struct nlist *nlist_p;
  2438.      char *name;
  2439.      struct file_entry *entry;
  2440. {
  2441.   register symbol *sp = getsym (name);
  2442.   register int type = nlist_p->n_type;
  2443.   int oldref = sp->referenced;
  2444.   int olddef = sp->defined;
  2445.  
  2446.   nlist_p->n_un.n_name = (char *) sp->refs;
  2447.   sp->refs = nlist_p;
  2448.  
  2449.   sp->referenced = 1;
  2450.   if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
  2451.     {
  2452.       if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
  2453.     sp->defined = type;
  2454.  
  2455.       if (oldref && !olddef)
  2456.     /* It used to be undefined and we're defining it.  */
  2457.     undefined_global_sym_count--;
  2458.  
  2459.       if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
  2460.     {
  2461.       /* First definition and it's common.  */
  2462.       common_defined_global_count++;
  2463.       sp->max_common_size = nlist_p->n_value;
  2464.     }
  2465.       else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
  2466.     {
  2467.       /* It used to be common and we're defining it as
  2468.          something else.  */
  2469.       common_defined_global_count--;
  2470.       sp->max_common_size = 0;
  2471.     }
  2472.       else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
  2473.       && sp->max_common_size < nlist_p->n_value)
  2474.     /* It used to be common and this is a new common entry to
  2475.        which we need to pay attention.  */
  2476.     sp->max_common_size = nlist_p->n_value;
  2477.  
  2478.       /* Are we defining it as a set element?  */
  2479.       if (SET_ELEMENT_P (type)
  2480.       && (!olddef || (olddef && sp->max_common_size)))
  2481.     set_vector_count++;
  2482.       /* As an indirection?  */
  2483.       else if (type == (N_INDR | N_EXT))
  2484.     {
  2485.       /* Indirect symbols value should be modified to point
  2486.          a symbol being equivalenced to. */
  2487.       nlist_p->n_value =
  2488.         (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
  2489.                      + entry->strings);
  2490.       if ((symbol *) nlist_p->n_value == sp)
  2491.         {
  2492.           /* Somebody redefined a symbol to be itself.  */
  2493.           fprintf (stderr, "%s: Symbol %s indirected to itself.\n",
  2494.                entry->filename, name);
  2495.           /* Rewrite this symbol as being a global text symbol
  2496.          with value 0.  */
  2497.           nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
  2498.           nlist_p->n_value = 0;
  2499.           /* Don't make the output executable.  */
  2500.           make_executable = 0;
  2501.         }
  2502.       else
  2503.         global_indirect_count++;
  2504.     }
  2505.     }
  2506.   else
  2507.     if (!oldref)
  2508. #ifndef DOLLAR_KLUDGE
  2509.       undefined_global_sym_count++;
  2510. #else
  2511.       {
  2512.     if (entry->superfile && type == (N_UNDF | N_EXT) && name[1] == '$')
  2513.       {
  2514.         /* This is an (ISI?) $-conditional; skip it */
  2515.         sp->referenced = 0;
  2516.         if (sp->trace)
  2517.           {
  2518.         fprintf (stderr, "symbol %s is a $-conditional ignored in ", sp->name);
  2519.         print_file_name (entry, stderr);
  2520.         fprintf (stderr, "\n");
  2521.           }
  2522.         return;
  2523.       }
  2524.     else
  2525.       undefined_global_sym_count++;
  2526.       }
  2527. #endif
  2528.  
  2529.   if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
  2530.     text_start = nlist_p->n_value;
  2531.  
  2532.   if (sp->trace)
  2533.     {
  2534.       register char *reftype;
  2535.       switch (type & ~N_EXT)
  2536.     {
  2537.     case N_UNDF:
  2538.       if (nlist_p->n_value)
  2539.         reftype = "defined as common";
  2540.       else reftype = "referenced";
  2541.       break;
  2542.  
  2543.     case N_ABS:
  2544.       reftype = "defined as absolute";
  2545.       break;
  2546.  
  2547.     case N_TEXT:
  2548.       reftype = "defined in text section";
  2549.       break;
  2550.  
  2551.     case N_DATA:
  2552.       reftype = "defined in data section";
  2553.       break;
  2554.  
  2555.     case N_BSS:
  2556.       reftype = "defined in BSS section";
  2557.       break;
  2558.  
  2559.     case N_SETT:
  2560.       reftype = "is a text set element";
  2561.       break;
  2562.  
  2563.     case N_SETD:
  2564.       reftype = "is a data set element";
  2565.       break;
  2566.  
  2567.     case N_SETB:
  2568.       reftype = "is a BSS set element";
  2569.       break;
  2570.  
  2571.     case N_SETA:
  2572.       reftype = "is an absolute set element";
  2573.       break;
  2574.  
  2575.     case N_SETV:
  2576.       reftype = "defined in data section as vector";
  2577.       break;
  2578.  
  2579.     case N_INDR:
  2580.       reftype = (char *) alloca (23 + strlen (((symbol *) nlist_p->n_value)->name));
  2581.       sprintf (reftype, "defined equivalent to %s",
  2582.            ((symbol *) nlist_p->n_value)->name);
  2583.       break;
  2584.  
  2585. #if TARGET_MACHINE==TARGET_SEQUENT
  2586.     case N_SHUNDF:
  2587.       reftype = "shared undf";
  2588.       break;
  2589.  
  2590. /* These conflict with cases above.
  2591.     case N_SHDATA:
  2592.       reftype = "shared data";
  2593.       break;
  2594.  
  2595.     case N_SHBSS:
  2596.       reftype = "shared BSS";
  2597.       break;
  2598. */
  2599. #endif
  2600.  
  2601.     default:
  2602.       reftype = "I don't know this type";
  2603.       break;
  2604.     }
  2605.  
  2606.       fprintf (stderr, "symbol %s %s in ", sp->name, reftype);
  2607.       print_file_name (entry, stderr);
  2608.       fprintf (stderr, "\n");
  2609.     }
  2610. }
  2611.  
  2612. /* This return 0 if the given file entry's symbol table does *not*
  2613.    contain the nlist point entry, and it returns the files entry
  2614.    pointer (cast to unsigned long) if it does. */
  2615.  
  2616. #if 0
  2617. unsigned long
  2618. contains_symbol (entry, n_ptr)
  2619.      struct file_entry *entry;
  2620.      register struct nlist *n_ptr;
  2621. {
  2622.   if (n_ptr >= entry->symbols &&
  2623.       n_ptr < (entry->symbols
  2624.            + (entry->syms_size / sizeof (struct nlist))))
  2625.     return (unsigned long) entry;
  2626.   return 0;
  2627. }
  2628. #endif
  2629.  
  2630.  
  2631. /* Searching libraries */
  2632.  
  2633. struct file_entry *decode_library_subfile ();
  2634. void linear_library (), symdef_library ();
  2635.  
  2636. /* Search the library ENTRY, already open on descriptor DESC.
  2637.    This means deciding which library members to load,
  2638.    making a chain of `struct file_entry' for those members,
  2639.    and entering their global symbols in the hash table.  */
  2640.  
  2641. void
  2642. search_library (desc, entry)
  2643.      int desc;
  2644.      struct file_entry *entry;
  2645. {
  2646.   int member_length;
  2647.   register char *name;
  2648.   register struct file_entry *subentry;
  2649.  
  2650.   if (!undefined_global_sym_count) return;
  2651.  
  2652.   /* Examine its first member, which starts SARMAG bytes in.  */
  2653.   subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  2654.   if (!subentry) return;
  2655.  
  2656.   name = subentry->filename;
  2657.   free (subentry);
  2658.  
  2659.   /* Search via __.SYMDEF if that exists, else linearly.  */
  2660.  
  2661.   if (!strcmp (name, "__.SYMDEF"))
  2662.     symdef_library (desc, entry, member_length);
  2663.   else
  2664.     linear_library (desc, entry);
  2665. }
  2666.  
  2667. /* Construct and return a file_entry for a library member.
  2668.    The library's file_entry is library_entry, and the library is open on DESC.
  2669.    SUBFILE_OFFSET is the byte index in the library of this member's header.
  2670.    We store the length of the member into *LENGTH_LOC.  */
  2671.  
  2672. struct file_entry *
  2673. decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
  2674.      int desc;
  2675.      struct file_entry *library_entry;
  2676.      int subfile_offset;
  2677.      int *length_loc;
  2678. {
  2679.   int bytes_read;
  2680.   register int namelen;
  2681.   int member_length;
  2682.   register char *name;
  2683.   struct ar_hdr hdr1;
  2684.   register struct file_entry *subentry;
  2685.  
  2686.   lseek (desc, subfile_offset, 0);
  2687.  
  2688.   bytes_read = read (desc, &hdr1, sizeof hdr1);
  2689.   if (!bytes_read)
  2690.     return 0;        /* end of archive */
  2691.  
  2692.   if (sizeof hdr1 != bytes_read)
  2693.     fatal_with_file ("malformed library archive ", library_entry);
  2694.  
  2695.   if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
  2696.     fatal_with_file ("malformatted header of archive member in ", library_entry);
  2697.  
  2698.   subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
  2699.   bzero (subentry, sizeof (struct file_entry));
  2700.  
  2701.   for (namelen = 0;
  2702.        namelen < sizeof hdr1.ar_name
  2703.        && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' '
  2704.        && hdr1.ar_name[namelen] != '/';
  2705.        namelen++);
  2706.  
  2707.   name = (char *) xmalloc (namelen+1);
  2708.   strncpy (name, hdr1.ar_name, namelen);
  2709.   name[namelen] = 0;
  2710.  
  2711.   subentry->filename = name;
  2712.   subentry->local_sym_name = name;
  2713.   subentry->symbols = 0;
  2714.   subentry->strings = 0;
  2715.   subentry->subfiles = 0;
  2716.   subentry->starting_offset = subfile_offset + sizeof hdr1;
  2717.   subentry->superfile = library_entry;
  2718.   subentry->library_flag = 0;
  2719.   subentry->header_read_flag = 0;
  2720.   subentry->just_syms_flag = 0;
  2721.   subentry->chain = 0;
  2722.   subentry->total_size = member_length;
  2723.  
  2724.   (*length_loc) = member_length;
  2725.  
  2726.   return subentry;
  2727. }
  2728.  
  2729. int subfile_wanted_p ();
  2730.  
  2731. /* Search a library that has a __.SYMDEF member.
  2732.    DESC is a descriptor on which the library is open.
  2733.      The file pointer is assumed to point at the __.SYMDEF data.
  2734.    ENTRY is the library's file_entry.
  2735.    MEMBER_LENGTH is the length of the __.SYMDEF data.  */
  2736.  
  2737. void
  2738. symdef_library (desc, entry, member_length)
  2739.      int desc;
  2740.      struct file_entry *entry;
  2741.      int member_length;
  2742. {
  2743.   int *symdef_data = (int *) xmalloc (member_length);
  2744.   register struct symdef *symdef_base;
  2745.   char *sym_name_base;
  2746.   int number_of_symdefs;
  2747.   int length_of_strings;
  2748.   int not_finished;
  2749.   int bytes_read;
  2750.   register int i;
  2751.   struct file_entry *prev = 0;
  2752.   int prev_offset = 0;
  2753.  
  2754.   bytes_read = read (desc, symdef_data, member_length);
  2755.   if (bytes_read != member_length)
  2756.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2757. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2758.   fix_byte_order(symdef_data, sizeof(*symdef_data));
  2759. #endif
  2760.   number_of_symdefs = *symdef_data / sizeof (struct symdef);
  2761.   if (number_of_symdefs < 0 ||
  2762.        number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) > member_length)
  2763.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2764.  
  2765.   symdef_base = (struct symdef *) (symdef_data + 1);
  2766. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2767.   for (i = 0; i < number_of_symdefs; ++i)
  2768.     {
  2769.       fix_byte_order(&symdef_base[i].symbol_name_string_index, sizeof(int));
  2770.       fix_byte_order(&symdef_base[i].library_member_offset, sizeof(int));
  2771.     }
  2772.   fix_byte_order(symdef_base + number_of_symdefs, sizeof(int));
  2773. #endif
  2774.   length_of_strings = *(int *) (symdef_base + number_of_symdefs);
  2775.  
  2776.   if (length_of_strings < 0
  2777.       || number_of_symdefs * sizeof (struct symdef) + length_of_strings
  2778.       + 2 * sizeof (int) != member_length)
  2779.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2780.  
  2781.   sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
  2782.  
  2783.   /* Check all the string indexes for validity.  */
  2784.  
  2785.   for (i = 0; i < number_of_symdefs; i++)
  2786.     {
  2787.       register int index = symdef_base[i].symbol_name_string_index;
  2788.       if (index < 0 || index >= length_of_strings
  2789.       || (index && *(sym_name_base + index - 1)))
  2790.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2791.     }
  2792.  
  2793.   /* Search the symdef data for members to load.
  2794.      Do this until one whole pass finds nothing to load.  */
  2795.  
  2796.   not_finished = 1;
  2797.   while (not_finished)
  2798.     {
  2799.       not_finished = 0;
  2800.  
  2801.       /* Scan all the symbols mentioned in the symdef for ones that we need.
  2802.      Load the library members that contain such symbols.  */
  2803.  
  2804.       for (i = 0;
  2805.        (i < number_of_symdefs
  2806.         && (undefined_global_sym_count || common_defined_global_count));
  2807.        i++)
  2808.     if (symdef_base[i].symbol_name_string_index >= 0)
  2809.       {
  2810.         register symbol *sp;
  2811.  
  2812.         sp = getsym_soft (sym_name_base
  2813.                   + symdef_base[i].symbol_name_string_index);
  2814.  
  2815.         /* If we find a symbol that appears to be needed, think carefully
  2816.            about the archive member that the symbol is in.  */
  2817.  
  2818.         if (sp && ((sp->referenced && !sp->defined)
  2819. #if 1        
  2820.                || (sp->defined && sp->max_common_size))
  2821. #endif
  2822.                )
  2823.           {
  2824.         int junk;
  2825.         register int j;
  2826.         register int offset = symdef_base[i].library_member_offset;
  2827.         struct file_entry *subentry;
  2828.  
  2829.         /* Don't think carefully about any archive member
  2830.            more than once in a given pass.  */
  2831.  
  2832.         if (prev_offset == offset)
  2833.           continue;
  2834.         prev_offset = offset;
  2835.  
  2836.         /* Read the symbol table of the archive member.  */
  2837.  
  2838.         subentry = decode_library_subfile (desc, entry, offset, &junk);
  2839.         if (subentry == 0)
  2840.           fatal ("invalid offset for %s in symbol table of %s",
  2841.              sym_name_base
  2842.              + symdef_base[i].symbol_name_string_index,
  2843.              entry->filename);
  2844.         read_entry_symbols (desc, subentry);
  2845.         subentry->strings = xmalloc (subentry->strs_size);
  2846.         read_entry_strings (desc, subentry);
  2847.  
  2848.         /* Now scan the symbol table and decide whether to load.  */
  2849.  
  2850.         if (!subfile_wanted_p (subentry))
  2851.           {
  2852.             free (subentry->symbols);
  2853.             free (subentry->strings);
  2854.             free (subentry);
  2855.           }
  2856.         else
  2857.           {
  2858.             /* This member is needed; load it.
  2859.                Since we are loading something on this pass,
  2860.                we must make another pass through the symdef data.  */
  2861.  
  2862.             not_finished = 1;
  2863.  
  2864.             enter_file_symbols (subentry);
  2865.  
  2866.             if (prev)
  2867.               prev->chain = subentry;
  2868.             else entry->subfiles = subentry;
  2869.             prev = subentry;
  2870.  
  2871.             /* Clear out this member's symbols from the symdef data
  2872.                so that following passes won't waste time on them.  */
  2873.  
  2874.             for (j = 0; j < number_of_symdefs; j++)
  2875.               {
  2876.             if (symdef_base[j].library_member_offset == offset)
  2877.               symdef_base[j].symbol_name_string_index = -1;
  2878.               }
  2879.  
  2880.             /* We'll read the strings again if we need them again.  */
  2881.             free (subentry->strings);
  2882.             subentry->strings = 0;
  2883.           }
  2884.           }
  2885.       }
  2886.     }
  2887.  
  2888.   free (symdef_data);
  2889. }
  2890.  
  2891.  
  2892. /* Handle a subentry for a file with no __.SYMDEF. */
  2893.  
  2894. process_subentry (desc, subentry, entry, prev_addr)
  2895.      int desc;
  2896.      register struct file_entry *subentry;
  2897.      struct file_entry **prev_addr, *entry;
  2898. {
  2899.   read_entry_symbols (desc, subentry);
  2900.   subentry->strings = (char *) alloca (subentry->strs_size);
  2901.   read_entry_strings (desc, subentry);
  2902.  
  2903.   if (!subfile_wanted_p (subentry))
  2904.     {
  2905.       free (subentry->symbols);
  2906.       free (subentry);
  2907.     }
  2908.   else
  2909.     {
  2910.       enter_file_symbols (subentry);
  2911.  
  2912.       if (*prev_addr)
  2913.     (*prev_addr)->chain = subentry;
  2914.       else
  2915.     entry->subfiles = subentry;
  2916.       *prev_addr = subentry;
  2917.       subentry->strings = 0; /* Since space will dissapear on return */
  2918.     }
  2919. }
  2920.  
  2921. /* Search a library that has no __.SYMDEF.
  2922.    ENTRY is the library's file_entry.
  2923.    DESC is the descriptor it is open on.  */
  2924.  
  2925. void
  2926. linear_library (desc, entry)
  2927.      int desc;
  2928.      struct file_entry *entry;
  2929. {
  2930.   struct file_entry *prev = 0;
  2931.   register int this_subfile_offset = SARMAG;
  2932.  
  2933.   while (undefined_global_sym_count || common_defined_global_count)
  2934.     {
  2935.       int member_length;
  2936.       register struct file_entry *subentry;
  2937.  
  2938.       subentry = decode_library_subfile (desc, entry, this_subfile_offset,
  2939.                      &member_length);
  2940.       if (!subentry) return;
  2941.  
  2942.       process_subentry (desc, subentry, entry, &prev);
  2943.       this_subfile_offset += member_length + sizeof (struct ar_hdr);
  2944.       if (this_subfile_offset & 1) this_subfile_offset++;
  2945.     }
  2946. }
  2947.  
  2948. /* ENTRY is an entry for a library member.
  2949.    Its symbols have been read into core, but not entered.
  2950.    Return nonzero if we ought to load this member.  */
  2951. int
  2952. subfile_wanted_p (entry)
  2953.      struct file_entry *entry;
  2954. {
  2955.   register struct nlist *p;
  2956.   register struct nlist *end
  2957.     = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2958. #ifdef DOLLAR_KLUDGE
  2959.   register int dollar_cond = 0;
  2960. #endif
  2961.  
  2962.   for (p = entry->symbols; p < end; p++)
  2963.     {
  2964.       register int type = p->n_type;
  2965.       register char *name = p->n_un.n_strx + entry->strings;
  2966.  
  2967.       /* If the symbol has an interesting definition, we could
  2968.      potentially want it.  */
  2969.       if (type & N_EXT
  2970.       && (type != (N_UNDF | N_EXT) || p->n_value
  2971.  
  2972. #ifdef DOLLAR_KLUDGE
  2973.            || name[1] == '$'
  2974. #endif
  2975.           )
  2976.       && !SET_ELEMENT_P (type)
  2977.       && !set_element_prefixed_p (name))
  2978.     {
  2979.       register symbol *sp = getsym_soft (name);
  2980.  
  2981. #ifdef DOLLAR_KLUDGE
  2982.       if (name[1] == '$')
  2983.         {
  2984.           sp = getsym_soft (&name[2]);
  2985.           dollar_cond = 1;
  2986.           if (!sp) continue;
  2987.           if (sp->referenced)
  2988.         {
  2989.           if (write_map)
  2990.             {
  2991.               print_file_name (entry, stdout);
  2992.               fprintf (stdout, " needed due to $-conditional %s\n", name);
  2993.             }
  2994.           return 1;
  2995.         }
  2996.           continue;
  2997.         }
  2998. #endif
  2999.  
  3000.       /* If this symbol has not been hashed, we can't be looking for it. */
  3001.  
  3002.       if (!sp) continue;
  3003.  
  3004.       if ((sp->referenced && !sp->defined)
  3005.           /* NB.  This needs to be changed so that, e.g., "int pipe;" won't import
  3006.          pipe() from the library.  But the bug fix kingdon made was wrong.  */
  3007.           || (sp->defined && sp->max_common_size))
  3008.         {
  3009.           /* This is a symbol we are looking for.  It is either
  3010.              not yet defined or defined as a common.  */
  3011. #ifdef DOLLAR_KLUDGE
  3012.           if (dollar_cond) continue;
  3013. #endif
  3014.           if (type == (N_UNDF | N_EXT))
  3015.         {
  3016.           /* Symbol being defined as common.
  3017.              Remember this, but don't load subfile just for this.  */
  3018.           /* If it didn't used to be common, up the count of
  3019.              common symbols.  */
  3020.           if (!sp->max_common_size)
  3021.             common_defined_global_count++;
  3022.           if (sp->max_common_size < p->n_value)
  3023.             sp->max_common_size = p->n_value;
  3024.           if (!sp->defined)
  3025.             undefined_global_sym_count--;
  3026.           sp->defined = 1;
  3027.           continue;
  3028.         }
  3029.  
  3030. #if TARGET==TARGET_SEQUENT
  3031.         /* Don't resolve common (data) symbols with text symbols*/
  3032.           if (type == (N_EXT | N_TEXT)) {
  3033.         int dontresolve = 0;
  3034.         struct nlist *p, *next;
  3035.  
  3036.         for (p = sp->refs; p; p = next) {
  3037.           if (p->n_value && (p->n_type == (N_UNDF | N_EXT))) {
  3038.               if (trace_files)
  3039.                   fprintf(stdout,
  3040.                       "refs check fail: symbol %s, ref type= 0x%x, ref value= 0x%x, sym type = 0x%x\n",
  3041.                       sp->name, p->n_type, p->n_value, type);
  3042.             dontresolve = 1;
  3043.             break;
  3044.           }
  3045.           next = (struct nlist *) p->n_un.n_name;
  3046.         }
  3047.         if (sp->trace) {
  3048.           fprintf(stdout, 
  3049.             "symbol %s can't use text sym def in file ", sp->name);
  3050.           print_file_name(entry, stdout);
  3051.           fprintf(stdout, "\n");
  3052.         }
  3053.         if (dontresolve)
  3054.           continue;
  3055.           }
  3056. #endif        
  3057.           if (write_map)
  3058.         {
  3059.           print_file_name (entry, stdout);
  3060.           fprintf (stdout, " needed due to %s\n", sp->name);
  3061.         }
  3062.           return 1;
  3063.         }
  3064.     }
  3065.     }
  3066.  
  3067.   return 0;
  3068. }
  3069.  
  3070. void consider_file_section_lengths (), relocate_file_addresses ();
  3071.  
  3072. /* Having entered all the global symbols and found the sizes of sections
  3073.    of all files to be linked, make all appropriate deductions from this data.
  3074.  
  3075.    We propagate global symbol values from definitions to references.
  3076.    We compute the layout of the output file and where each input file's
  3077.    contents fit into it.  */
  3078.  
  3079. void
  3080. digest_symbols ()
  3081. {
  3082.   register int i;
  3083.   int setv_fill_count = 0;
  3084.  
  3085.   if (trace_files)
  3086.     fprintf (stderr, "Digesting symbol information:\n\n");
  3087.  
  3088.   /* Initialize the text_start address; this depends on the output file formats.  */
  3089.  
  3090.   initialize_text_start ();
  3091.  
  3092.   text_size = text_header_size;
  3093.  
  3094.   /* Compute total size of sections */
  3095.  
  3096.   each_file (consider_file_section_lengths, 0);
  3097.  
  3098.   /* If necessary, pad text section to full page in the file.
  3099.      Include the padding in the text segment size.  */
  3100.  
  3101. #ifdef NMAGIC
  3102.   if (magic == ZMAGIC || magic == NMAGIC)
  3103. #else /* NMAGIC */
  3104. #ifdef SMAGIC
  3105.   if (magic == ZMAGIC || magic == SMAGIC)
  3106. #else /* SMAGIC */
  3107.   if (magic == ZMAGIC)
  3108. #endif /* SMAGIC */
  3109. #endif /* NMAGIC */
  3110.     {
  3111.       int text_end = text_size + N_TXTOFF (outheader);
  3112.       text_pad = ((text_end + page_size - 1) & (- page_size)) - text_end;
  3113.       text_size += text_pad;
  3114.     }
  3115.  
  3116.   outheader.a_text = text_size;
  3117. #if TARGET_MACHINE==TARGET_SEQUENT
  3118.   outheader.a_text += N_ADDRADJ (outheader);
  3119. #endif
  3120.  
  3121.   /* Make the data segment address start in memory on a suitable boundary.  */
  3122.  
  3123.   if (! Tdata_flag_specified)
  3124.     data_start = N_DATADDR (outheader) + text_start - N_TXTADDR (outheader);
  3125. #ifdef foobar
  3126.   /* Make sure bss starts out aligned as much as anyone can want.  */
  3127.  
  3128.   data_size = (data_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  3129. #endif
  3130.  
  3131.   if (Z_flag_specified)
  3132.       data_start += data_gap;
  3133.  
  3134.   /* Set up the set element vector */
  3135.  
  3136.   if (!relocatable_output)
  3137.     {
  3138.       /* The set sector size is the number of set elements + a word
  3139.          for each symbol for the length word at the beginning of the
  3140.      vector, plus a word for each symbol for a zero at the end of
  3141.      the vector (for incremental linking).  */
  3142.       set_sect_size =
  3143.         (2 * set_symbol_count + set_vector_count) * sizeof (unsigned long);
  3144.       set_sect_start = data_start + data_size;
  3145.       data_size += set_sect_size;
  3146.       set_vectors = (unsigned long *) xmalloc (set_sect_size);
  3147. #if 1
  3148.       setv_fill_count = 0;
  3149. #endif      
  3150.     }
  3151.  
  3152.   /* Compute start addresses of each file's sections and symbols.  */
  3153.  
  3154.   each_full_file (relocate_file_addresses, 0);
  3155.  
  3156.   /* Now, for each symbol, verify that it is defined globally at most once.
  3157.      Put the global value into the symbol entry.
  3158.      Common symbols are allocated here, in the BSS section.
  3159.      Each defined symbol is given a '->defined' field
  3160.       which is the correct N_ code for its definition,
  3161.       except in the case of common symbols with -r.
  3162.      Then make all the references point at the symbol entry
  3163.      instead of being chained together. */
  3164.  
  3165.   defined_global_sym_count = 0;
  3166.  
  3167.   for (i = 0; i < TABSIZE; i++)
  3168.     {
  3169.       register symbol *sp;
  3170.       for (sp = symtab[i]; sp; sp = sp->link)
  3171.     {
  3172.       /* For each symbol */
  3173.       register struct nlist *p, *next;
  3174.       int defs = 0, com = sp->max_common_size;
  3175.       struct nlist *first_definition;
  3176.       for (p = sp->refs; p; p = next)
  3177.         {
  3178.           register int type = p->n_type;
  3179.  
  3180.           if (SET_ELEMENT_P (type))
  3181.         {
  3182.           if (output_style == OUTPUT_RELOCATABLE)
  3183.             fatal ("internal: global ref to set element with -r");
  3184.           if (!defs++)
  3185.             {
  3186.               sp->value = set_sect_start
  3187.             + setv_fill_count++ * sizeof (unsigned long);
  3188.               sp->defined = N_SETV | N_EXT;
  3189.               first_definition = p;
  3190.             }
  3191.           else if ((sp->defined & ~N_EXT) != N_SETV)
  3192.             {
  3193.               sp->multiply_defined = 1;
  3194.               multiple_def_count++;
  3195.             }
  3196.           set_vectors[setv_fill_count++] = p->n_value;
  3197.         }
  3198.           else if ((type & N_EXT) && type != (N_UNDF | N_EXT))
  3199.         {
  3200.           /* non-common definition */
  3201.           if (defs++ && sp->value != p->n_value)
  3202.             {
  3203.               sp->multiply_defined = 1;
  3204.               multiple_def_count++;
  3205.             }
  3206.           sp->value = p->n_value;
  3207.           sp->defined = type;
  3208.           first_definition = p;
  3209.         }
  3210.           next = (struct nlist *) p->n_un.n_name;
  3211.           p->n_un.n_name = (char *) sp;
  3212.         }
  3213.       /* Allocate as common if defined as common and not defined for real */
  3214.       if (com && !defs)
  3215.         {
  3216.           if (output_style != OUTPUT_RELOCATABLE || force_common_definition)
  3217.         {
  3218.           int align = sizeof (int);
  3219.  
  3220.           /* Round up to nearest sizeof (int).  I don't know
  3221.              whether this is necessary or not (given that
  3222.              alignment is taken care of later), but it's
  3223.              traditional, so I'll leave it in.  Note that if
  3224.              this size alignment is ever removed, ALIGN above
  3225.              will have to be initialized to 1 instead of
  3226.              sizeof (int).  */
  3227.  
  3228.           com = (com + sizeof (int) - 1) & (- sizeof (int));
  3229.  
  3230.           while (!(com & align))
  3231.             align <<= 1;
  3232.  
  3233.           align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align;
  3234.  
  3235.           bss_size = ((((bss_size + data_size + data_start)
  3236.                   + (align - 1)) & (- align))
  3237.                   - data_size - data_start);
  3238.  
  3239.           sp->value = data_start + data_size + bss_size;
  3240.           sp->defined = N_BSS | N_EXT;
  3241.           bss_size += com;
  3242.           if (write_map)
  3243.             printf ("Allocating common %s: %x at %x\n",
  3244.                 sp->name, com, sp->value);
  3245.         }
  3246.           else
  3247.         {
  3248.           sp->defined = 0;
  3249.           undefined_global_sym_count++;
  3250.         }
  3251.         }
  3252.       /* Set length word at front of vector and zero byte at end.
  3253.          Reverse the vector itself to put it in file order.  */
  3254.       if ((sp->defined & ~N_EXT) == N_SETV)
  3255.         {
  3256.           unsigned long length_word_index =
  3257.             (sp->value - set_sect_start) / sizeof (unsigned long);
  3258.           unsigned long i, tmp;
  3259.  
  3260.           set_vectors[length_word_index] =
  3261.             setv_fill_count - 1 - length_word_index;
  3262.           /* Reverse the vector.  */
  3263.           for (i = 1;
  3264.            i < (setv_fill_count - length_word_index - 1) / 2 + 1;
  3265.            i++)
  3266.         {
  3267.           tmp = set_vectors[length_word_index + i];
  3268.           set_vectors[length_word_index + i] =
  3269.             set_vectors[setv_fill_count - i];
  3270.           set_vectors[setv_fill_count - i] = tmp;
  3271.         }
  3272.  
  3273.           set_vectors[setv_fill_count++] = 0;
  3274.         }
  3275.       if (sp->defined)
  3276.         defined_global_sym_count++;
  3277.     }
  3278.     }
  3279.  
  3280. #ifdef foobar
  3281.   /* Make sure end of bss is aligned as much as anyone can want.  */
  3282.  
  3283.   bss_size = (bss_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  3284. #endif
  3285.  
  3286.   if (end_symbol)        /* These are null if -r.  */
  3287.     {
  3288.       etext_symbol->value = text_size + text_start;
  3289.       edata_symbol->value = data_start + data_size;
  3290.       end_symbol->value = data_start + data_size + bss_size;
  3291.     }
  3292.  
  3293.   /* Figure the data_pad now, so that it overlaps with the bss addresses.  */
  3294.  
  3295.   if (specified_data_size && specified_data_size > data_size)
  3296.     data_pad = specified_data_size - data_size;
  3297.  
  3298. #ifdef SMAGIC
  3299.   if (magic == SMAGIC || magic == ZMAGIC)
  3300. #else
  3301.   if (magic == ZMAGIC)
  3302. #endif
  3303.     data_pad = ((data_pad + data_size + page_size - 1) & (- page_size))
  3304.     - data_size;
  3305.  
  3306.   bss_size -= data_pad;
  3307.   if (bss_size < 0) bss_size = 0;
  3308.  
  3309.   data_size += data_pad;
  3310. }
  3311.  
  3312. /* Accumulate the section sizes of input file ENTRY
  3313.    into the section sizes of the output file.  */
  3314.  
  3315. void
  3316. consider_file_section_lengths (entry)
  3317.      register struct file_entry *entry;
  3318. {
  3319.   if (entry->just_syms_flag)
  3320.     return;
  3321.  
  3322.   entry->text_start_address = text_size;
  3323.   /* If there were any vectors, we need to chop them off */
  3324.   text_size += entry->text_size;
  3325.   entry->data_start_address = data_size;
  3326.   data_size += entry->data_size;
  3327.   entry->bss_start_address = bss_size;
  3328.   bss_size += entry->bss_size;
  3329.  
  3330.   text_reloc_size += entry->text_reloc_size;
  3331.   data_reloc_size += entry->data_reloc_size;
  3332. }
  3333.  
  3334. /* Determine where the sections of ENTRY go into the output file,
  3335.    whose total section sizes are already known.
  3336.    Also relocate the addresses of the file's local and debugger symbols.  */
  3337.  
  3338. void
  3339. relocate_file_addresses (entry)
  3340.      register struct file_entry *entry;
  3341. {
  3342.   entry->text_start_address += text_start;
  3343.  
  3344.   /* Note that `data_start' and `data_size' have not yet been adjusted
  3345.      for the portion of data_pad which overlaps with bss.  If they had
  3346.      been, we would get the wrong results here.  */
  3347.   entry->data_start_address += data_start;
  3348.   entry->bss_start_address += data_start + data_size;
  3349.  
  3350.   {
  3351.     register struct nlist *p;
  3352.     register struct nlist *end
  3353.       = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3354.  
  3355.     for (p = entry->symbols; p < end; p++)
  3356.       {
  3357.     /* If this belongs to a section, update it by the section's start address */
  3358.     register int type = p->n_type & ~N_EXT;
  3359.  
  3360.     switch (type)
  3361.       {
  3362.       case N_TEXT:
  3363.       case N_SETT:
  3364.         p->n_value += entry->text_start_address - entry->orig_text_address;
  3365.         break;
  3366.       case N_DATA:
  3367.       case N_SETV:
  3368.       case N_SETD:
  3369.         /* Data segment symbol.  Subtract the address of the
  3370.            data segment in the input file, and add the address
  3371.            of this input file's data segment in the output file.  */
  3372.         p->n_value +=
  3373.           entry->data_start_address - entry->orig_data_address;
  3374.         break;
  3375.       case N_BSS:
  3376.       case N_SETB:
  3377.         /* likewise for symbols with value in BSS.  */
  3378.         p->n_value += entry->bss_start_address - entry->orig_bss_address;
  3379.         break;
  3380.       }
  3381.       }
  3382.   }
  3383. }
  3384.  
  3385. void describe_file_sections (), list_file_locals ();
  3386.  
  3387. /* Print a complete or partial map of the output file.  */
  3388.  
  3389. void
  3390. print_symbols (outfile)
  3391.      FILE *outfile;
  3392. {
  3393.   register int i;
  3394.  
  3395.   fprintf (outfile, "\nFiles:\n\n");
  3396.  
  3397.   each_file (describe_file_sections, outfile);
  3398.  
  3399.   fprintf (outfile, "\nGlobal symbols:\n\n");
  3400.  
  3401.   for (i = 0; i < TABSIZE; i++)
  3402.     {
  3403.       register symbol *sp;
  3404.       for (sp = symtab[i]; sp; sp = sp->link)
  3405.     {
  3406.       if (sp->defined == 1)
  3407.         fprintf (outfile, "  %s: common, length 0x%x\n", sp->name, sp->max_common_size);
  3408.       if (sp->defined)
  3409.         fprintf (outfile, "  %s: 0x%x\n", sp->name, sp->value);
  3410.       else if (sp->referenced)
  3411.         fprintf (outfile, "  %s: undefined\n", sp->name);
  3412.     }
  3413.     }
  3414.  
  3415.   each_file (list_file_locals, outfile);
  3416. }
  3417.  
  3418. void
  3419. describe_file_sections (entry, outfile)
  3420.      struct file_entry *entry;
  3421.      FILE *outfile;
  3422. {
  3423.   fprintf (outfile, "  ");
  3424.   print_file_name (entry, outfile);
  3425.   if (entry->just_syms_flag)
  3426.     fprintf (outfile, " symbols only\n", 0);
  3427.   else
  3428.     fprintf (outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n",
  3429.          entry->text_start_address, entry->text_size,
  3430.          entry->data_start_address, entry->data_size,
  3431.          entry->bss_start_address, entry->bss_size);
  3432. }
  3433.  
  3434. void
  3435. list_file_locals (entry, outfile)
  3436.      struct file_entry *entry;
  3437.      FILE *outfile;
  3438. {
  3439.   register struct nlist
  3440.     *p,
  3441.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3442.  
  3443.   entry->strings = (char *) alloca (entry->strs_size);
  3444.   read_entry_strings (file_open (entry), entry);
  3445.  
  3446.   fprintf (outfile, "\nLocal symbols of ");
  3447.   print_file_name (entry, outfile);
  3448.   fprintf (outfile, ":\n\n");
  3449.  
  3450.   for (p = entry->symbols; p < end; p++)
  3451.     /* If this is a definition,
  3452.        update it if necessary by this file's start address.  */
  3453.     if (!(p->n_type & (N_STAB | N_EXT)))
  3454.       fprintf (outfile, "  %s: 0x%x\n",
  3455.            entry->strings + p->n_un.n_strx, p->n_value);
  3456.  
  3457.   entry->strings = 0;        /* All done with them.  */
  3458. }
  3459.  
  3460.  
  3461. /* Static vars for do_warnings and subroutines of it */
  3462. int list_unresolved_refs;    /* List unresolved refs */
  3463. int list_warning_symbols;    /* List warning syms */
  3464. int list_multiple_defs;        /* List multiple definitions */
  3465.  
  3466. /*
  3467.  * Structure for communication between do_file_warnings and it's
  3468.  * helper routines.  Will in practice be an array of three of these:
  3469.  * 0) Current line, 1) Next line, 2) Source file info.
  3470.  */
  3471. struct line_debug_entry
  3472. {
  3473.   int line;
  3474.   char *filename;
  3475.   struct nlist *Sym;
  3476. };
  3477.  
  3478. void qsort ();
  3479. /*
  3480.  * Helper routines for do_file_warnings.
  3481.  */
  3482.  
  3483. /* Return an integer less than, equal to, or greater than 0 as per the
  3484.    relation between the two relocation entries.  Used by qsort.  */
  3485.  
  3486. int
  3487. relocation_entries_relation (rel1, rel2)
  3488.      struct relocation_info *rel1, *rel2;
  3489. {
  3490.   return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2);
  3491. }
  3492.  
  3493. /* Moves to the next debugging symbol in the file.  USE_DATA_SYMBOLS
  3494.    determines the type of the debugging symbol to look for (DSLINE or
  3495.    SLINE).  STATE_POINTER keeps track of the old and new locatiosn in
  3496.    the file.  It assumes that state_pointer[1] is valid; ie
  3497.    that it.sym points into some entry in the symbol table.  If
  3498.    state_pointer[1].sym == 0, this routine should not be called.  */
  3499.  
  3500. int
  3501. next_debug_entry (use_data_symbols, state_pointer)
  3502.      register int use_data_symbols;
  3503.      /* Next must be passed by reference! */
  3504.      struct line_debug_entry state_pointer[3];
  3505. {
  3506.   register struct line_debug_entry
  3507.     *current = state_pointer,
  3508.     *next = state_pointer + 1,
  3509.     /* Used to store source file */
  3510.     *source = state_pointer + 2;
  3511.   struct file_entry *entry = (struct file_entry *) source->Sym;
  3512.  
  3513.   current->Sym = next->Sym;
  3514.   current->line = next->line;
  3515.   current->filename = next->filename;
  3516.  
  3517.   while (++(next->Sym) < (entry->symbols
  3518.               + entry->header.a_syms/sizeof (struct nlist)))
  3519.     {
  3520.       /* n_type is a char, and N_SOL, N_EINCL and N_BINCL are > 0x80, so
  3521.        * may look negative...therefore, must mask to low bits
  3522.        */
  3523.       switch (next->Sym->n_type & 0xff) 
  3524.     {
  3525.     case N_SLINE:
  3526.       if (use_data_symbols) continue;
  3527.       next->line = next->Sym->n_desc;
  3528.       return 1;
  3529.     case N_DSLINE:
  3530.       if (!use_data_symbols) continue;
  3531.       next->line = next->Sym->n_desc;
  3532.       return 1;
  3533. #ifdef HAVE_SUN_STABS
  3534.     case N_EINCL:
  3535.       next->filename = source->filename;
  3536.       continue;
  3537. #endif
  3538.     case N_SO:
  3539.       source->filename = next->Sym->n_un.n_strx + entry->strings;
  3540.       source->line++;
  3541. #ifdef HAVE_SUN_STABS
  3542.     case N_BINCL:
  3543. #endif
  3544.     case N_SOL:
  3545.       next->filename =
  3546.         next->Sym->n_un.n_strx + entry->strings;
  3547.     default:
  3548.       continue;
  3549.     }
  3550.     }
  3551.   next->Sym = (struct nlist *) 0;
  3552.   return 0;
  3553. }
  3554.  
  3555. /* Create a structure to save the state of a scan through the debug
  3556.    symbols.  USE_DATA_SYMBOLS is set if we should be scanning for
  3557.    DSLINE's instead of SLINE's.  entry is the file entry which points
  3558.    at the symbols to use.  */
  3559.  
  3560. struct line_debug_entry *
  3561. init_debug_scan (use_data_symbols, entry)
  3562.      int use_data_symbols;
  3563.      struct file_entry *entry;
  3564. {
  3565.   struct line_debug_entry
  3566.     *state_pointer =
  3567.         (struct line_debug_entry *)
  3568.         xmalloc (3 * sizeof (struct line_debug_entry));
  3569.   register struct line_debug_entry
  3570.     *current = state_pointer,
  3571.     *next = state_pointer + 1,
  3572.     *source = state_pointer + 2; /* Used to store source file */
  3573.  
  3574.   struct nlist *tmp;
  3575.  
  3576.   for (tmp = entry->symbols;
  3577.        tmp < (entry->symbols
  3578.           + entry->syms_size/sizeof (struct nlist));
  3579.        tmp++)
  3580.     if (tmp->n_type == (int) N_SO)
  3581.       break;
  3582.  
  3583.   if (tmp >= (entry->symbols
  3584.           + entry->syms_size/sizeof (struct nlist)))
  3585.     {
  3586.       /* I believe this translates to "We lose" */
  3587.       current->filename = next->filename = entry->filename;
  3588.       current->line = next->line = -1;
  3589.       current->Sym = next->Sym = (struct nlist *) 0;
  3590.       return state_pointer;
  3591.     }
  3592.  
  3593.   next->line = source->line = 0;
  3594.   next->filename = source->filename
  3595.     = (tmp->n_un.n_strx + entry->strings);
  3596.   source->Sym = (struct nlist *) entry;
  3597.   next->Sym = tmp;
  3598.  
  3599.   next_debug_entry (use_data_symbols, state_pointer); /* To setup next */
  3600.  
  3601.   if (!next->Sym)        /* No line numbers for this section; */
  3602.                 /* setup output results as appropriate */
  3603.     {
  3604.       if (source->line)
  3605.     {
  3606.       current->filename = source->filename = entry->filename;
  3607.       current->line = -1;    /* Don't print lineno */
  3608.     }
  3609.       else
  3610.     {
  3611.       current->filename = source->filename;
  3612.       current->line = 0;
  3613.     }
  3614.       return state_pointer;
  3615.     }
  3616.  
  3617.  
  3618.   next_debug_entry (use_data_symbols, state_pointer); /* To setup current */
  3619.  
  3620.   return state_pointer;
  3621. }
  3622.  
  3623. /* Takes an ADDRESS (in either text or data space) and a STATE_POINTER
  3624.    which describes the current location in the implied scan through
  3625.    the debug symbols within the file which ADDRESS is within, and
  3626.    returns the source line number which corresponds to ADDRESS.  */
  3627.  
  3628. int
  3629. address_to_line (address, state_pointer)
  3630.      unsigned long address;
  3631.      /* Next must be passed by reference! */
  3632.      struct line_debug_entry state_pointer[3];
  3633. {
  3634.   struct line_debug_entry
  3635.     *current = state_pointer,
  3636.     *next = state_pointer + 1;
  3637.   struct line_debug_entry *tmp_pointer;
  3638.  
  3639.   int use_data_symbols;
  3640.  
  3641.   if (next->Sym)
  3642.     use_data_symbols = (next->Sym->n_type & N_TYPE) == N_DATA;
  3643.   else
  3644.     return current->line;
  3645.  
  3646.   /* Go back to the beginning if we've already passed it.  */
  3647.   if (current->Sym->n_value > address)
  3648.     {
  3649.       tmp_pointer = init_debug_scan (use_data_symbols,
  3650.                      (struct file_entry *)
  3651.                      ((state_pointer + 2)->Sym));
  3652.       state_pointer[0] = tmp_pointer[0];
  3653.       state_pointer[1] = tmp_pointer[1];
  3654.       state_pointer[2] = tmp_pointer[2];
  3655.       free (tmp_pointer);
  3656.     }
  3657.  
  3658.   /* If we're still in a bad way, return -1, meaning invalid line.  */
  3659.   if (current->Sym->n_value > address)
  3660.     return -1;
  3661.  
  3662.   while (next->Sym
  3663.      && next->Sym->n_value <= address
  3664.      && next_debug_entry (use_data_symbols, state_pointer))
  3665.     ;
  3666.   return current->line;
  3667. }
  3668.  
  3669.  
  3670. /* Macros for manipulating bitvectors.  */
  3671. #define    BIT_SET_P(bv, index)    ((bv)[(index) >> 3] & 1 << ((index) & 0x7))
  3672. #define    SET_BIT(bv, index)    ((bv)[(index) >> 3] |= 1 << ((index) & 0x7))
  3673.  
  3674. /* This routine will scan through the relocation data of file ENTRY,
  3675.    printing out references to undefined symbols and references to
  3676.    symbols defined in files with N_WARNING symbols.  If DATA_SEGMENT
  3677.    is non-zero, it will scan the data relocation segment (and use
  3678.    N_DSLINE symbols to track line number); otherwise it will scan the
  3679.    text relocation segment.  Warnings will be printed on the output
  3680.    stream OUTFILE.  Eventually, every nlist symbol mapped through will
  3681.    be marked in the NLIST_BITVECTOR, so we don't repeat ourselves when
  3682.    we scan the nlists themselves.  */
  3683.  
  3684. do_relocation_warnings (entry, data_segment, outfile, nlist_bitvector)
  3685.      struct file_entry *entry;
  3686.      int data_segment;
  3687.      FILE *outfile;
  3688.      unsigned char *nlist_bitvector;
  3689. {
  3690.   struct relocation_info
  3691.     *reloc_start = data_segment ? entry->datarel : entry->textrel,
  3692.     *reloc;
  3693.   int reloc_size =
  3694.     (data_segment ? entry->header.a_drsize : entry->header.a_trsize)
  3695.        / sizeof (struct relocation_info);
  3696.   int start_of_segment =
  3697.     (data_segment ? entry->data_start_address : entry->text_start_address);
  3698.   struct nlist *start_of_syms = entry->symbols;
  3699.   struct line_debug_entry *state_pointer =
  3700.     init_debug_scan (data_segment != 0, entry);
  3701.   register struct line_debug_entry
  3702.     *current = state_pointer;
  3703.   /* Assigned to generally static values; should not be written into.  */
  3704.   char *errfmt;
  3705.   /* Assigned to alloca'd values cand copied into; should be freed
  3706.      when done.  */
  3707.   char *errmsg;
  3708.   int invalidate_line_number;
  3709.  
  3710.   /* We need to sort the relocation info here.  Sheesh, so much effort
  3711.      for one lousy error optimization. */
  3712.  
  3713.   qsort (reloc_start, reloc_size, sizeof (struct relocation_info),
  3714.      relocation_entries_relation);
  3715.  
  3716.   for (reloc = reloc_start;
  3717.        reloc < (reloc_start + reloc_size);
  3718.        reloc++)
  3719.     {
  3720.       register struct nlist *s;
  3721.       register symbol *g;
  3722.  
  3723.       /* If the relocation isn't resolved through a symbol, continue */
  3724.       if (!RELOC_EXTERN_P(reloc))
  3725.     continue;
  3726.  
  3727.       s = &(entry->symbols[RELOC_SYMBOL(reloc)]);
  3728.  
  3729.       /* Local symbols shouldn't ever be used by relocation info, so
  3730.      the next should be safe.
  3731.      This is, of course, wrong.  References to local BSS symbols can be
  3732.      the targets of relocation info, and they can (must) be
  3733.      resolved through symbols.  However, these must be defined properly,
  3734.      (the assembler would have caught it otherwise), so we can
  3735.      ignore these cases.  */
  3736.       if (!(s->n_type & N_EXT))
  3737.     continue;
  3738.  
  3739.       g = (symbol *) s->n_un.n_name;
  3740.       errmsg = 0;
  3741.  
  3742.       if (!g->defined && list_unresolved_refs) /* Reference */
  3743.     {
  3744.       /* Mark as being noted by relocation warning pass.  */
  3745.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3746.  
  3747.       if (g->undef_refs >= MAX_UREFS_PRINTED)    /* Listed too many */
  3748.         continue;
  3749.  
  3750.       /* Undefined symbol which we should mention */
  3751.  
  3752.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3753.         {
  3754.           errfmt = "More undefined symbol %s refs follow";
  3755.           invalidate_line_number = 1;
  3756.         }
  3757.       else
  3758.         {
  3759.           errfmt = "Undefined symbol %s referenced from %s segment";
  3760.           invalidate_line_number = 0;
  3761.         }
  3762.     }
  3763.       else                         /* Defined */
  3764.     {
  3765.       /* Potential symbol warning here */
  3766.       if (!g->warning) continue;
  3767.  
  3768.       /* Mark as being noted by relocation warning pass.  */
  3769.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3770.       
  3771.       errfmt = 0;
  3772.       errmsg = g->warning;
  3773.       invalidate_line_number = 0;
  3774.     }
  3775.       
  3776.  
  3777.       /* If errfmt == 0, errmsg has already been defined.  */
  3778.       if (errfmt != 0)
  3779.     {
  3780.       char *nm;
  3781.  
  3782.       if (demangler == NULL || (nm = (*demangler)(g->name)) == NULL)
  3783.         nm = g->name;
  3784.       errmsg = (char *) xmalloc (strlen (errfmt) + strlen (nm) + 1);
  3785.       sprintf (errmsg, errfmt, nm, data_segment ? "data" : "text");
  3786.       if (nm != g->name)
  3787.         free (nm);
  3788.     }
  3789.  
  3790.       address_to_line (RELOC_ADDRESS (reloc) + start_of_segment,
  3791.                state_pointer);
  3792.  
  3793.       if (current->line >=0)
  3794.     {
  3795.       fprintf (outfile, "%s:%d (", current->filename,
  3796.            invalidate_line_number ? 0 : current->line);
  3797.       print_file_name (entry, outfile);
  3798.       fprintf (outfile, "): %s\n", errmsg);
  3799.     }
  3800.       else
  3801.     {
  3802.       print_file_name(entry, outfile);
  3803.       fprintf(outfile, ": %s\n", errmsg);
  3804.     }
  3805.  
  3806.       if (errfmt != 0)
  3807.     free (errmsg);
  3808.     }
  3809.  
  3810.   free (state_pointer);
  3811. }
  3812.  
  3813. /* Print on OUTFILE a list of all warnings generated by references
  3814.    and/or definitions in the file ENTRY.  List source file and line
  3815.    number if possible, just the .o file if not. */
  3816.  
  3817. void
  3818. do_file_warnings (entry, outfile)
  3819.      struct file_entry *entry;
  3820.      FILE *outfile;
  3821. {
  3822.   int number_of_syms = entry->header.a_syms / sizeof (struct nlist);
  3823.   unsigned char *nlist_bitvector =
  3824.     (unsigned char *) alloca ((number_of_syms >> 3) + 1);
  3825.   struct line_debug_entry *text_scan, *data_scan;
  3826.   int i;
  3827.   char *errfmt, *file_name;
  3828.   int line_number;
  3829.   int dont_allow_symbol_name;
  3830.  
  3831.   bzero (nlist_bitvector, (number_of_syms >> 3) + 1);
  3832.  
  3833.   /* Read in the files strings if they aren't available */
  3834.   if (!entry->strings)
  3835.     {
  3836.       int desc;
  3837.  
  3838.       entry->strings = (char *) alloca (entry->strs_size);
  3839.       desc = file_open (entry);
  3840.       read_entry_strings (desc, entry);
  3841.     }
  3842.  
  3843.   read_file_relocation (entry);
  3844.  
  3845.   /* Do text warnings based on a scan through the relocation info.  */
  3846.   do_relocation_warnings (entry, 0, outfile, nlist_bitvector);
  3847.  
  3848.   /* Do data warnings based on a scan through the relocation info.  */
  3849.   do_relocation_warnings (entry, 1, outfile, nlist_bitvector);
  3850.  
  3851.   /* Scan through all of the nlist entries in this file and pick up
  3852.      anything that the scan through the relocation stuff didn't.  */
  3853.  
  3854.   text_scan = init_debug_scan (0, entry);
  3855.   data_scan = init_debug_scan (1, entry);
  3856.  
  3857.   for (i = 0; i < number_of_syms; i++)
  3858.     {
  3859.       struct nlist *s;
  3860.       struct glosym *g;
  3861.  
  3862.       s = entry->symbols + i;
  3863.  
  3864.       if (!(s->n_type & N_EXT))
  3865.     continue;
  3866.  
  3867.       g = (symbol *) s->n_un.n_name;
  3868.       dont_allow_symbol_name = 0;
  3869.  
  3870.       if (list_multiple_defs && g->multiply_defined)
  3871.     {
  3872.       errfmt = "Definition of symbol %s (multiply defined)";
  3873.       switch (s->n_type)
  3874.         {
  3875.         case N_TEXT | N_EXT:
  3876.           line_number = address_to_line (s->n_value, text_scan);
  3877.           file_name = text_scan[0].filename;
  3878.           break;
  3879.         case N_DATA | N_EXT:
  3880.           line_number = address_to_line (s->n_value, data_scan);
  3881.           file_name = data_scan[0].filename;
  3882.           break;
  3883.         case N_SETA | N_EXT:
  3884.         case N_SETT | N_EXT:
  3885.         case N_SETD | N_EXT:
  3886.         case N_SETB | N_EXT:
  3887.           if (g->multiply_defined == 2)
  3888.         continue;
  3889.           errfmt = "First set element definition of symbol %s (multiply defined)";
  3890.           break;
  3891.         default:
  3892.           continue;        /* Don't print out multiple defs
  3893.                    at references.  */
  3894.         }
  3895.     }
  3896.       else if (BIT_SET_P (nlist_bitvector, i))
  3897.     continue;
  3898.       else if (list_unresolved_refs && !g->defined)
  3899.     {
  3900.       if (g->undef_refs >= MAX_UREFS_PRINTED)
  3901.         continue;
  3902.  
  3903.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3904.         errfmt = "More undefined \"%s\" refs follow";
  3905.       else
  3906.         errfmt = "Undefined symbol \"%s\" referenced";
  3907.       line_number = -1;
  3908.     }
  3909.       else if (g->warning)
  3910.     {
  3911.       /* There are two cases in which we don't want to
  3912.          do this.  The first is if this is a definition instead of
  3913.          a reference.  The second is if it's the reference used by
  3914.          the warning stabs itself.  */
  3915.       if (s->n_type != (N_EXT | N_UNDF)
  3916.           || (i && (s-1)->n_type == N_WARNING))
  3917.         continue;
  3918.  
  3919.       errfmt = g->warning;
  3920.       line_number = -1;
  3921.       dont_allow_symbol_name = 1;
  3922.     }
  3923.       else
  3924.     continue;
  3925.  
  3926.       if (line_number == -1)
  3927.     fprintf (outfile, "%s: ", entry->filename);
  3928.       else
  3929.     fprintf (outfile, "%s:%d: ", file_name, line_number);
  3930.  
  3931.       if (dont_allow_symbol_name)
  3932.       fprintf (outfile, "%s", errfmt);
  3933.       else
  3934.       {
  3935.     char *nm;
  3936.     if (demangler != NULL && (nm = (*demangler)(g->name)) != NULL)
  3937.       {
  3938.         fprintf (outfile, errfmt, nm);
  3939.         free (nm);
  3940.       } else
  3941.         fprintf (outfile, errfmt, g->name);
  3942.       }
  3943.  
  3944.       fputc ('\n', outfile);
  3945.     }
  3946.   free (text_scan);
  3947.   free (data_scan);
  3948.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  3949. }
  3950.  
  3951. do_warnings (outfile)
  3952.      FILE *outfile;
  3953. {
  3954.   list_unresolved_refs = output_style != OUTPUT_RELOCATABLE && undefined_global_sym_count;
  3955.   list_warning_symbols = warning_count;
  3956.   list_multiple_defs = multiple_def_count != 0;
  3957.  
  3958.   if (!(list_unresolved_refs ||
  3959.     list_warning_symbols ||
  3960.     list_multiple_defs      ))
  3961.     /* No need to run this routine */
  3962.     return;
  3963.  
  3964.   each_file (do_file_warnings, outfile);
  3965.   if (trace_files)
  3966.       printf("undefined_global_sym_count= %d, multiple_def_count= %d\n",
  3967.          undefined_global_sym_count, multiple_def_count);
  3968.   if (list_unresolved_refs || list_multiple_defs)
  3969.     make_executable = 0;
  3970. }
  3971.  
  3972. /* Write the output file */
  3973.  
  3974. void
  3975. write_output ()
  3976. {
  3977.   struct stat statbuf;
  3978.   int filemode;
  3979.  
  3980.   outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  3981.   if (outdesc < 0) perror_name (output_filename);
  3982.  
  3983.   if (fstat (outdesc, &statbuf) < 0)
  3984.     perror_name (output_filename);
  3985.  
  3986.   filemode = statbuf.st_mode;
  3987.  
  3988.   chmod (output_filename, filemode & ~0111);
  3989.  
  3990.   /* Output the a.out header.  */
  3991.   write_header ();
  3992.  
  3993.   /* Output the text and data segments, relocating as we go.  */
  3994.   write_text ();
  3995.   write_data ();
  3996.  
  3997.   /* Output the merged relocation info, if requested with `-r'.  */
  3998.   if (relocatable_output)
  3999.     write_rel ();
  4000.  
  4001.   /* Output the symbol table (both globals and locals).  */
  4002.   write_syms ();
  4003.  
  4004.   /* Copy any GDB symbol segments from input files.  */
  4005.   write_symsegs ();
  4006.  
  4007.   close (outdesc);
  4008.  
  4009.   if (chmod (output_filename, filemode | 0111) == -1)
  4010.     perror_name (output_filename);
  4011. }
  4012.  
  4013. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  4014.  
  4015. void
  4016. write_header ()
  4017. {
  4018.   N_SET_MAGIC (outheader, magic);
  4019.   outheader.a_text = text_size;
  4020.   if (T_flag_specified)
  4021.       outheader.a_text += text_start;
  4022. #if TARGET_MACHINE==TARGET_SEQUENT
  4023.   outheader.a_text += N_ADDRADJ (outheader);
  4024.   if (entry_symbol == 0)
  4025.       entry_symbol = getsym("start");
  4026. #endif
  4027.   outheader.a_data = data_size;
  4028.   outheader.a_bss = bss_size;
  4029.   outheader.a_entry = (entry_symbol ? entry_symbol->value
  4030.                : text_start + entry_offset);
  4031. #ifdef COFF_ENCAPSULATE
  4032.   if (need_coff_header)
  4033.     {
  4034.       /* We are encapsulating BSD format within COFF format.  */
  4035.       struct coffscn *tp, *dp, *bp;
  4036.  
  4037.       tp = &coffheader.scns[0];
  4038.       dp = &coffheader.scns[1];
  4039.       bp = &coffheader.scns[2];
  4040.  
  4041.       strcpy (tp->s_name, ".text");
  4042.       tp->s_paddr = text_start;
  4043.       tp->s_vaddr = text_start;
  4044.       tp->s_size = text_size;
  4045.       tp->s_scnptr = sizeof (struct coffheader) + sizeof (struct exec);
  4046.       tp->s_relptr = 0;
  4047.       tp->s_lnnoptr = 0;
  4048.       tp->s_nreloc = 0;
  4049.       tp->s_nlnno = 0;
  4050.       tp->s_flags = 0x20;
  4051.       strcpy (dp->s_name, ".data");
  4052.       dp->s_paddr = data_start;
  4053.       dp->s_vaddr = data_start;
  4054.       dp->s_size = data_size;
  4055.       dp->s_scnptr = tp->s_scnptr + tp->s_size;
  4056.       dp->s_relptr = 0;
  4057.       dp->s_lnnoptr = 0;
  4058.       dp->s_nreloc = 0;
  4059.       dp->s_nlnno = 0;
  4060.       dp->s_flags = 0x40;
  4061.       strcpy (bp->s_name, ".bss");
  4062.       bp->s_paddr = dp->s_vaddr + dp->s_size;
  4063.       bp->s_vaddr = bp->s_paddr;
  4064.       bp->s_size = bss_size;
  4065.       bp->s_scnptr = 0;
  4066.       bp->s_relptr = 0;
  4067.       bp->s_lnnoptr = 0;
  4068.       bp->s_nreloc = 0;
  4069.       bp->s_nlnno = 0;
  4070.       bp->s_flags = 0x80;
  4071.  
  4072.       coffheader.f_magic = COFF_MAGIC;
  4073.       coffheader.f_nscns = 3;
  4074.       /* store an unlikely time so programs can
  4075.        * tell that there is a bsd header
  4076.        */
  4077.       coffheader.f_timdat = 1;
  4078.       coffheader.f_symptr = 0;
  4079.       coffheader.f_nsyms = 0;
  4080.       coffheader.f_opthdr = 28;
  4081.       coffheader.f_flags = 0x103;
  4082.       /* aouthdr */
  4083.       coffheader.magic = ZMAGIC;
  4084.       coffheader.vstamp = 0;
  4085.       coffheader.tsize = tp->s_size;
  4086.       coffheader.dsize = dp->s_size;
  4087.       coffheader.bsize = bp->s_size;
  4088.       coffheader.entry = outheader.a_entry;
  4089.       coffheader.text_start = tp->s_vaddr;
  4090.       coffheader.data_start = dp->s_vaddr;
  4091.     }
  4092. #endif
  4093. #if TARGET==TARGET_SEQUENT
  4094.     if (SMAGIC == magic) {
  4095.     char *target_ptr; 
  4096.     long n; 
  4097.  
  4098.     outheader.a_gdtbl = gdt_filler; 
  4099.     if (sizeof(instr) > sizeof(outheader.a_bootstrap)) {
  4100.         fatal("a_bootstrap too small for code"); 
  4101.     } 
  4102.     n = outheader.a_entry; 
  4103.     target_ptr = &instr[sizeof(instr) - 4];
  4104.     target_ptr[0] = n & 0xff; 
  4105.     target_ptr[1] = (n >> 8) & 0xff; 
  4106.     target_ptr[2] = (n >> 16) & 0xff; 
  4107.     target_ptr[3] = (n >> 24) & 0xff; 
  4108.     bcopy(instr, (char *)outheader.a_bootstrap, sizeof(instr)); 
  4109.     }
  4110. #endif
  4111.  
  4112.   if (strip_symbols == STRIP_ALL)
  4113.     nsyms = 0;
  4114.   else
  4115.     {
  4116.       nsyms = (defined_global_sym_count
  4117.            + undefined_global_sym_count);
  4118.       if (discard_locals == DISCARD_L)
  4119.     nsyms += non_L_local_sym_count;
  4120.       else if (discard_locals == DISCARD_NONE)
  4121.     nsyms += local_sym_count;
  4122.       /* One extra for following reference on indirects */
  4123.       if (output_style == OUTPUT_RELOCATABLE)
  4124. #ifndef NeXT
  4125.     nsyms += set_symbol_count + global_indirect_count;
  4126. #else
  4127.         nsyms += set_symbol_count;
  4128. #endif
  4129.     }
  4130.  
  4131.   if (strip_symbols == STRIP_NONE)
  4132.     nsyms += debugger_sym_count;
  4133.  
  4134.   outheader.a_syms = nsyms * sizeof (struct nlist);
  4135.  
  4136.   if (output_style == OUTPUT_RELOCATABLE)
  4137.     {
  4138.       outheader.a_trsize = text_reloc_size;
  4139.       outheader.a_drsize = data_reloc_size;
  4140.     }
  4141.   else
  4142.     {
  4143.       outheader.a_trsize = 0;
  4144.       outheader.a_drsize = 0;
  4145.     }
  4146.  
  4147. #ifdef COFF_ENCAPSULATE
  4148.   if (need_coff_header)
  4149.     mywrite (&coffheader, sizeof coffheader, 1, outdesc);
  4150. #endif
  4151. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4152.   fix_exec_header_byte_order(&outheader);
  4153. #endif
  4154.   mywrite (&outheader, sizeof (struct exec), 1, outdesc);
  4155. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4156.   fix_exec_header_byte_order(&outheader);
  4157. #endif
  4158.  
  4159.   /* Output whatever padding is required in the executable file
  4160.      between the header and the start of the text.  */
  4161.  
  4162. #ifndef COFF_ENCAPSULATE
  4163.   padfile (N_TXTOFF (outheader) - sizeof outheader, outdesc);
  4164. #endif
  4165.  
  4166.  
  4167.   if (T_flag_specified)
  4168.       padfile (text_start - sizeof(struct exec), outdesc);
  4169.  
  4170. }
  4171.  
  4172. #endif
  4173.  
  4174. #ifdef MACH_O
  4175.  
  4176. /* Stuff pertaining to creating Mach-O files. */
  4177.  
  4178. /* Convert the Mach-O style n_sect references into something the rest
  4179.    of the loader can understand.  */
  4180.  
  4181. void
  4182. translate_mach_o_symbols (entry)
  4183.      struct file_entry *entry;
  4184. {
  4185.   int i, n, g;
  4186.   struct nlist *sym;
  4187.  
  4188.   n = entry->syms_size / sizeof (struct nlist);
  4189.   for (i = 0; i < n; ++i)
  4190.     if (((sym = &entry->symbols[i])->n_type & ~N_EXT) == N_SECT)
  4191.       {
  4192.     if (sym->n_sect == entry->text_ordinal)
  4193.       sym->n_type = (sym->n_type & N_EXT) | N_TEXT;
  4194.     else if (sym->n_sect == entry->data_ordinal)
  4195.       sym->n_type = (sym->n_type & N_EXT) | N_DATA;
  4196.     else if (sym->n_sect == entry->bss_ordinal)
  4197.       sym->n_type = (sym->n_type & N_EXT) | N_BSS;
  4198.     else
  4199.       fatal_with_file ("unknown section referenced in symbols of ", entry);
  4200.     sym->n_sect = 0;
  4201.       }
  4202.     else if ((sym = &entry->symbols[i])->n_type == N_SLINE)
  4203.       {
  4204.     if (sym->n_sect == entry->text_ordinal)
  4205.       sym->n_type = N_SLINE;
  4206.     else if (sym->n_sect == entry->data_ordinal)
  4207.       sym->n_type = N_DSLINE;
  4208.     else if (sym->n_sect == entry->bss_ordinal)
  4209.       sym->n_type = N_BSLINE;
  4210.     else
  4211.       fatal_with_file ("unknown section referenced in debugging symbols of ", entry);
  4212.       }
  4213. }
  4214.  
  4215. /* Convert Mach-O style relocation info into a.out style relocation
  4216.    info internally.  */
  4217. void
  4218. translate_mach_o_relocation (entry, reloc, count)
  4219.      struct file_entry *entry;
  4220.      struct relocation_info *reloc;
  4221.      int count;
  4222. {
  4223.   int i;
  4224.  
  4225.   for (i = 0; i < count; ++i)
  4226.     if (!RELOC_EXTERN_P(&reloc[i]))
  4227.       if (RELOC_TYPE(&reloc[i]) == R_ABS)
  4228.     RELOC_TYPE(&reloc[i]) = N_ABS;
  4229.       else if (RELOC_TYPE(&reloc[i]) == entry->text_ordinal)
  4230.     RELOC_TYPE(&reloc[i]) = N_TEXT;
  4231.       else if (RELOC_TYPE(&reloc[i]) == entry->data_ordinal)
  4232.     RELOC_TYPE(&reloc[i]) = N_DATA;
  4233.       else if (RELOC_TYPE(&reloc[i]) == entry->bss_ordinal)
  4234.     RELOC_TYPE(&reloc[i]) = N_BSS;
  4235.       else
  4236.     fatal_with_file ("unknown section ordinal in relocation info of ", entry);
  4237. }
  4238.  
  4239. /* Header structure for OUTPUT_RELOCATABLE.  */
  4240.  
  4241. struct
  4242. {
  4243.   struct mach_header header;
  4244.   struct segment_command segment;
  4245.   struct section text;
  4246.   struct section data;
  4247.   struct section bss;
  4248.   struct symtab_command symtab;
  4249. #ifdef LC_SYMSEG
  4250.   struct symseg_command symseg;
  4251. #endif
  4252. } m_object;
  4253.  
  4254. #ifdef NeXT
  4255. #define CPU_TYPE CPU_TYPE_MC68030
  4256. #define CPU_SUBTYPE CPU_SUBTYPE_NeXT
  4257. #define THREAD_FLAVOR NeXT_THREAD_STATE_REGS
  4258. #define THREAD_COUNT NeXT_THREAD_STATE_REGS_COUNT
  4259. typedef struct NeXT_thread_state_regs thread_state;
  4260. #define thread_state_entry_field pc
  4261. #endif
  4262.  
  4263. /* Header structure for all executable output forms.  */
  4264.  
  4265. struct
  4266. {
  4267.   struct mach_header header;
  4268.   struct segment_command pagezero;
  4269.   struct segment_command text_segment;
  4270.   struct section text;
  4271.   struct segment_command data_segment;
  4272.   struct section data;
  4273.   struct section bss;
  4274.   struct thread_command unixthread;
  4275.   unsigned long int flavor;
  4276.   unsigned long int count;
  4277.   thread_state state;
  4278.   struct symtab_command symtab;
  4279. #ifdef LC_SYMSEG
  4280.   struct symseg_command symseg;
  4281. #endif
  4282. } m_exec;
  4283.  
  4284. /* Compute text_start and text_header_size for an a.out file.  */
  4285.  
  4286. void
  4287. initialize_mach_o_text_start ()
  4288. {
  4289.   if (output_style != OUTPUT_RELOCATABLE)
  4290.     {
  4291.       text_header_size = sizeof m_exec;
  4292.       if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  4293.     /* We reserve the first page of an executable to trap NULL dereferences.  */
  4294.     text_start = page_size;
  4295.     }
  4296. }
  4297.  
  4298. /* Compute data_start once text_size is known.  */
  4299.  
  4300. void
  4301. initialize_mach_o_data_start ()
  4302. {
  4303.   if (! Tdata_flag_specified)
  4304.     data_start = text_start + text_size;
  4305. }
  4306.  
  4307. /* Compute offsets of various pieces of the Mach-O output file.  */
  4308. void
  4309. compute_mach_o_section_offsets ()
  4310. {
  4311.   int header_size, trsize, drsize;
  4312.  
  4313.   switch (output_style)
  4314.     {
  4315.     case OUTPUT_RELOCATABLE:
  4316.       header_size = sizeof m_object;
  4317.       break;
  4318.     default:
  4319.       header_size = sizeof m_exec;
  4320.       break;
  4321.     }
  4322.  
  4323.   if (strip_symbols == STRIP_ALL)
  4324.     nsyms = 0;
  4325.   else
  4326.     {
  4327.       nsyms = (defined_global_sym_count
  4328.            + undefined_global_sym_count);
  4329.       if (discard_locals == DISCARD_L)
  4330.     nsyms += non_L_local_sym_count;
  4331.       else if (discard_locals == DISCARD_NONE)
  4332.     nsyms += local_sym_count;
  4333.       /* One extra for following reference on indirects */
  4334.       if (output_style == OUTPUT_RELOCATABLE)
  4335. #ifndef NeXT
  4336.     nsyms += set_symbol_count + global_indirect_count;
  4337. #else
  4338.         nsyms += set_symbol_count;
  4339. #endif
  4340.     }
  4341.  
  4342.   if (strip_symbols == STRIP_NONE)
  4343.     nsyms += debugger_sym_count;
  4344.  
  4345.   if (output_style != OUTPUT_RELOCATABLE)
  4346.     output_text_offset = header_size;
  4347.   output_data_offset = output_text_offset + text_size;
  4348.   output_trel_offset = output_data_offset + data_size;
  4349.   if (output_style == OUTPUT_RELOCATABLE)
  4350.     trsize = text_reloc_size, drsize = data_reloc_size;
  4351.   else
  4352.     trsize = drsize = 0;
  4353.   output_drel_offset = output_trel_offset + trsize;
  4354.   output_syms_offset = output_drel_offset + drsize;
  4355.   output_strs_offset = output_syms_offset + nsyms * sizeof (struct nlist);
  4356. }
  4357.  
  4358. /* Compute more section offsets once the size of the string table is known.  */
  4359. void
  4360. compute_more_mach_o_section_offsets ()
  4361. {
  4362.   output_symseg_offset = output_strs_offset + output_strs_size;
  4363. }
  4364.  
  4365. /* Write the Mach-O header once everything else is known.  */
  4366.  
  4367. void
  4368. write_mach_o_header ()
  4369. {
  4370.   struct mach_header header;
  4371.   struct section text, data, bss;
  4372.   struct symtab_command symtab;
  4373. #ifdef LC_SYMSEG
  4374.   struct symseg_command symseg;
  4375. #endif
  4376.   thread_state state;
  4377.  
  4378.   lseek (outdesc, 0L, 0);
  4379.  
  4380.  
  4381.   header.magic = MH_MAGIC;
  4382.   header.cputype = CPU_TYPE;
  4383.   header.cpusubtype = CPU_SUBTYPE;
  4384.   header.filetype = output_style == OUTPUT_RELOCATABLE ? MH_OBJECT : MH_EXECUTE;
  4385. #ifdef LC_SYMSEG
  4386.   switch (output_style)
  4387.     {
  4388.     case OUTPUT_RELOCATABLE:
  4389.       header.ncmds = 3;
  4390.       header.sizeofcmds = sizeof m_object - sizeof header;
  4391.       break;
  4392.     default:
  4393.       header.ncmds = 6;
  4394.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4395.       break;
  4396.     }
  4397. #else
  4398.   switch (output_style)
  4399.     {
  4400.     case OUTPUT_RELOCATABLE:
  4401.       header.ncmds = 2;
  4402.       header.sizeofcmds = sizeof m_object - sizeof header;
  4403.       break;
  4404.     default:
  4405.       header.ncmds = 5;
  4406.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4407.       break;
  4408.     }
  4409. #endif
  4410.   header.flags = undefined_global_sym_count ? 0 : MH_NOUNDEFS;
  4411.  
  4412.   bzero((char *) &text, sizeof text);
  4413.   strncpy(text.sectname, SECT_TEXT, sizeof text.sectname);
  4414.   strncpy(text.segname, SEG_TEXT, sizeof text.segname);
  4415.   text.addr = text_start;
  4416.   text.size = text_size;
  4417.   text.offset = output_text_offset;
  4418.   text.align = text.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4419.   text.reloff = output_trel_offset;
  4420.   text.nreloc = output_style == OUTPUT_RELOCATABLE
  4421.     ? text_reloc_size / sizeof (struct relocation_info) : 0;
  4422.   text.flags = 0;
  4423.  
  4424.   bzero((char *) &data, sizeof data);
  4425.   strncpy(data.sectname, SECT_DATA, sizeof data.sectname);
  4426.   strncpy(data.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4427.       sizeof data.segname);
  4428.   data.addr = data_start;
  4429.   data.size = data_size;
  4430.   data.offset = output_data_offset;
  4431.   data.align = data.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4432.   data.reloff = output_drel_offset;
  4433.   data.nreloc = output_style == OUTPUT_RELOCATABLE
  4434.     ? data_reloc_size / sizeof (struct relocation_info) : 0;
  4435.   data.flags = 0;
  4436.  
  4437.   bzero((char *) &bss, sizeof bss);
  4438.   strncpy(bss.sectname, SECT_BSS, sizeof data.sectname);
  4439.   strncpy(bss.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4440.       sizeof bss.segname);
  4441.   bss.addr = data_start + data_size;
  4442.   bss.size = bss_size;
  4443.   bss.align = bss.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4444.   bss.reloff = 0;
  4445.   bss.nreloc = 0;
  4446.   bss.flags = S_ZEROFILL;
  4447.  
  4448.   symtab.cmd = LC_SYMTAB;
  4449.   symtab.cmdsize = sizeof symtab;
  4450.   symtab.symoff = output_syms_offset;
  4451.   symtab.nsyms = output_syms_size / sizeof (struct nlist);
  4452.   symtab.stroff = output_strs_offset;
  4453.   symtab.strsize = output_strs_size;
  4454.  
  4455. #ifdef LC_SYMSEG
  4456.   symseg.cmd = LC_SYMSEG;
  4457.   symseg.cmdsize = sizeof symseg;
  4458.   symseg.offset = output_symseg_offset;
  4459.   symseg.size = output_symseg_size;
  4460. #endif
  4461.  
  4462.   switch (output_style)
  4463.     {
  4464.     case OUTPUT_RELOCATABLE:
  4465.       m_object.header = header;
  4466.       m_object.segment.cmd = LC_SEGMENT;
  4467.       m_object.segment.cmdsize = sizeof (struct segment_command) + 3 * sizeof (struct section);
  4468.       strncpy(m_object.segment.segname, SEG_TEXT, sizeof m_object.segment.segname);
  4469.       m_object.segment.vmaddr = 0;
  4470.       m_object.segment.vmsize = text.size + data.size + bss.size;
  4471.       m_object.segment.fileoff = text.offset;
  4472.       m_object.segment.filesize = text.size + data.size;
  4473.       m_object.segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4474.       m_object.segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4475.       m_object.segment.nsects = 3;
  4476.       m_object.segment.flags = 0;
  4477.       m_object.text = text;
  4478.       m_object.data = data;
  4479.       m_object.bss = bss;
  4480.       m_object.symtab = symtab;
  4481. #ifdef LC_SYMSEG
  4482.       m_object.symseg = symseg;
  4483. #endif
  4484.       mywrite((char *) &m_object, 1, sizeof m_object, outdesc);
  4485.       break;
  4486.  
  4487.     default:
  4488.       m_exec.header = header;
  4489.       m_exec.pagezero.cmd = LC_SEGMENT;
  4490.       m_exec.pagezero.cmdsize = sizeof (struct segment_command);
  4491.       strncpy(m_exec.pagezero.segname, SEG_PAGEZERO, sizeof m_exec.pagezero.segname);
  4492.       m_exec.pagezero.vmaddr = 0;
  4493.       m_exec.pagezero.vmsize = page_size;
  4494.       m_exec.pagezero.fileoff = 0;
  4495.       m_exec.pagezero.filesize = 0;
  4496.       m_exec.pagezero.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4497.       m_exec.pagezero.initprot = 0;
  4498.       m_exec.pagezero.nsects = 0;
  4499.       m_exec.pagezero.flags = 0;
  4500.       m_exec.text_segment.cmd = LC_SEGMENT;
  4501.       m_exec.text_segment.cmdsize = sizeof (struct segment_command) + sizeof (struct section);
  4502.       strncpy(m_exec.text_segment.segname, SEG_TEXT, sizeof m_exec.text_segment.segname);
  4503.       m_exec.text_segment.vmaddr = text_start;
  4504.       m_exec.text_segment.vmsize = text_size;
  4505.       m_exec.text_segment.fileoff = output_text_offset;
  4506.       m_exec.text_segment.filesize = text_size;
  4507.       m_exec.text_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4508.       m_exec.text_segment.initprot = VM_PROT_READ | VM_PROT_EXECUTE;
  4509.       if (output_style == OUTPUT_WRITABLE_TEXT)
  4510.     m_exec.text_segment.initprot |= VM_PROT_WRITE;
  4511.       m_exec.text_segment.nsects = 1;
  4512.       m_exec.text_segment.flags = 0;
  4513.       m_exec.text = text;
  4514.       m_exec.data_segment.cmd = LC_SEGMENT;
  4515.       m_exec.data_segment.cmdsize = sizeof (struct segment_command) + 2 * sizeof (struct section);
  4516.       strncpy(m_exec.data_segment.segname, SEG_DATA, sizeof m_exec.data_segment.segname);
  4517.       m_exec.data_segment.vmaddr = data_start;
  4518.       m_exec.data_segment.vmsize = data_size + bss_size;
  4519.       m_exec.data_segment.fileoff = output_data_offset;
  4520.       m_exec.data_segment.filesize = data_size;
  4521.       m_exec.data_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4522.       m_exec.data_segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4523.       m_exec.data_segment.nsects = 2;
  4524.       m_exec.data_segment.flags = 0;
  4525.       m_exec.data = data;
  4526.       m_exec.bss = bss;
  4527.       m_exec.unixthread.cmd = LC_UNIXTHREAD;
  4528.       m_exec.unixthread.cmdsize
  4529.     = sizeof (struct thread_command) + 2 * sizeof (long int) + sizeof (thread_state);
  4530.       m_exec.flavor = THREAD_FLAVOR;
  4531.       m_exec.count = THREAD_COUNT;
  4532.       m_exec.state.thread_state_entry_field = entry_symbol
  4533.     ? entry_symbol->value : text_start + text_header_size;
  4534.       m_exec.symtab = symtab;
  4535. #ifdef LC_SYMSEG
  4536.       m_exec.symseg = symseg;
  4537. #endif
  4538.       mywrite((char *) &m_exec, 1, sizeof m_exec, outdesc);
  4539.       break;
  4540.     }
  4541. }
  4542.  
  4543. /* Translate a.out style symbols into Mach-O style symbols.  */
  4544.  
  4545. void
  4546. generate_mach_o_symbols (syms, nsyms)
  4547.      struct nlist *syms;
  4548.      int nsyms;
  4549. {
  4550.   int i;
  4551.  
  4552.   for (i = 0; i < nsyms; ++i)
  4553.     switch (syms[i].n_type)
  4554.       {
  4555.       case N_TEXT:
  4556.       case N_TEXT | N_EXT:
  4557.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4558.     syms[i].n_sect = 1;    /* text section ordinal */
  4559.     break;
  4560.       case N_DATA:
  4561.       case N_DATA | N_EXT:
  4562.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4563.     syms[i].n_sect = 2;    /* data section ordinal */
  4564.     break;
  4565.       case N_BSS:
  4566.       case N_BSS | N_EXT:
  4567.     syms[i].n_type = syms[i].n_type & N_EXT | N_BSS;
  4568.     syms[i].n_sect = 3;    /* bss section ordinal */
  4569.     break;
  4570.       case N_SLINE:
  4571.     syms[i].n_type = N_SLINE;
  4572.     syms[i].n_sect = 1;    /* text section ordinal */
  4573.     break;
  4574.       case N_DSLINE:
  4575.     syms[i].n_type = N_SLINE;
  4576.     syms[i].n_sect = 2;    /* data section ordinal */
  4577.     break;
  4578.       case N_BSLINE:
  4579.     syms[i].n_type = N_SLINE;
  4580.     syms[i].n_sect = 3;    /* bss section ordinal */
  4581.     break;
  4582.       }
  4583. }
  4584.  
  4585. /* Translate a.out style relocation info into Mach-O style relocation
  4586.    info.  */
  4587.  
  4588. void
  4589. generate_mach_o_relocations (reloc, nreloc)
  4590.      struct relocation_info *reloc;
  4591.      int nreloc;
  4592. {
  4593.   int i;
  4594.  
  4595.   for (i = 0; i < nreloc; ++i)
  4596.     if (!RELOC_EXTERN_P (&reloc[i]))
  4597.       switch (RELOC_TYPE (&reloc[i]))
  4598.     {
  4599.     case N_ABS:
  4600.     case N_ABS | N_EXT:
  4601.       RELOC_TYPE (&reloc[i]) = R_ABS;
  4602.       break;
  4603.     case N_TEXT:
  4604.     case N_TEXT | N_EXT:
  4605.       RELOC_TYPE (&reloc[i]) = 1; /* output text section ordinal */
  4606.       break;
  4607.     case N_DATA:
  4608.     case N_DATA | N_EXT:
  4609.       RELOC_TYPE (&reloc[i]) = 2; /* output data section ordinal */
  4610.       break;
  4611.     case N_BSS:
  4612.     case N_BSS | N_EXT:
  4613.       RELOC_TYPE (&reloc[i]) = 3; /* output bss section ordinal */
  4614.       break;
  4615.     }
  4616. }
  4617.  
  4618. #endif
  4619.  
  4620. /* The following functions are simple switches according to the
  4621.    output style.  */
  4622.  
  4623. /* Compute text_start and text_header_size as appropriate for the
  4624.    output format.  */
  4625.  
  4626. void
  4627. initialize_text_start ()
  4628. {
  4629. #ifdef A_OUT
  4630.   if (output_file_type == IS_A_OUT)
  4631.     {
  4632.       initialize_a_out_text_start ();
  4633.       return;
  4634.     }
  4635. #endif
  4636. #ifdef MACH_O
  4637.   if (output_file_type == IS_MACH_O)
  4638.     {
  4639.       initialize_mach_o_text_start ();
  4640.       return;
  4641.     }
  4642. #endif
  4643.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4644. }
  4645.  
  4646. /* Initialize data_start as appropriate to the output format, once text_size
  4647.    is known.  */
  4648.  
  4649. void
  4650. initialize_data_start ()
  4651. {
  4652. #ifdef A_OUT
  4653.   if (output_file_type == IS_A_OUT)
  4654.     {
  4655.       initialize_a_out_data_start ();
  4656.       return;
  4657.     }
  4658. #endif
  4659. #ifdef MACH_O
  4660.   if (output_file_type == IS_MACH_O)
  4661.     {
  4662.       initialize_mach_o_data_start ();
  4663.       return;
  4664.     }
  4665. #endif
  4666.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4667. }
  4668.  
  4669. /* Compute offsets of the various sections within the output file.  */
  4670.  
  4671. void
  4672. compute_section_offsets ()
  4673. {
  4674. #ifdef A_OUT
  4675.   if (output_file_type == IS_A_OUT)
  4676.     {
  4677.       compute_a_out_section_offsets ();
  4678.       return;
  4679.     }
  4680. #endif
  4681. #ifdef MACH_O
  4682.   if (output_file_type == IS_MACH_O)
  4683.     {
  4684.       compute_mach_o_section_offsets ();
  4685.       return;
  4686.     }
  4687. #endif
  4688.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4689. }
  4690.  
  4691. /* Compute more section offsets, once the size of the string table
  4692.    is finalized.  */
  4693. void
  4694. compute_more_section_offsets ()
  4695. {
  4696. #ifdef A_OUT
  4697.   if (output_file_type == IS_A_OUT)
  4698.     {
  4699.       compute_more_a_out_section_offsets ();
  4700.       return;
  4701.     }
  4702. #endif
  4703. #ifdef MACH_O
  4704.   if (output_file_type == IS_MACH_O)
  4705.     {
  4706.       compute_more_mach_o_section_offsets ();
  4707.       return;
  4708.     }
  4709. #endif
  4710.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4711. }
  4712.  
  4713. /* Write the output file header, once everything is known.  */
  4714. void
  4715. write_header ()
  4716. {
  4717. #ifdef A_OUT
  4718.   if (output_file_type == IS_A_OUT)
  4719.     {
  4720.       write_a_out_header ();
  4721.       return;
  4722.     }
  4723. #endif
  4724. #ifdef MACH_O
  4725.   if (output_file_type == IS_MACH_O)
  4726.     {
  4727.       write_mach_o_header ();
  4728.       return;
  4729.     }
  4730. #endif
  4731.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4732. }
  4733.  
  4734. /* Write the output file */
  4735.  
  4736. void
  4737. write_output ()
  4738. {
  4739.   struct stat statbuf;
  4740.   int filemode, mask;
  4741.  
  4742.   /* Remove the old file in case it is owned by someone else.
  4743.      This prevents spurious "not owner" error messages.
  4744.      Don't check for errors from unlink; we don't really care
  4745.      whether it worked.
  4746.  
  4747.      Note that this means that if the output file is hard linked,
  4748.      the other names will still have the old contents.  This is
  4749.      the way Unix ld works; I'm going to consider it a feature.  */
  4750.   (void) unlink (output_filename);
  4751.   
  4752.   outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  4753.   if (outdesc < 0) perror_name (output_filename);
  4754.  
  4755.   if (fstat (outdesc, &statbuf) < 0)
  4756.     perror_name (output_filename);
  4757.  
  4758.   filemode = statbuf.st_mode;
  4759.  
  4760.   chmod (output_filename, filemode & ~0111);
  4761.  
  4762.   /* Calculate the offsets of the various pieces of the output file.  */
  4763.   compute_section_offsets ();
  4764.  
  4765.   /* Output the text and data segments, relocating as we go.  */
  4766.   write_text ();
  4767.   write_data ();
  4768.  
  4769.   /* Output the merged relocation info, if requested with `-r'.  */
  4770.   if (output_style == OUTPUT_RELOCATABLE)
  4771.     write_rel ();
  4772.  
  4773.   /* Output the symbol table (both globals and locals).  */
  4774.   write_syms ();
  4775.  
  4776.   /* At this point the total size of the symbol table and string table
  4777.      are finalized.  */
  4778.   compute_more_section_offsets ();
  4779.  
  4780.   /* Copy any GDB symbol segments from input files.  */
  4781.   write_symsegs ();
  4782.  
  4783.   /* Now that everything is known about the output file, write its header.  */
  4784.   write_header ();
  4785.  
  4786.   close (outdesc);
  4787.  
  4788.   mask = umask (0);
  4789.   umask (mask);
  4790.  
  4791.   if (chmod (output_filename, filemode | (0111 & ~mask)) == -1)
  4792.     perror_name (output_filename);
  4793. }
  4794.  
  4795. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  4796.  
  4797. /* Relocate the text segment of each input file
  4798.    and write to the output file.  */
  4799.  
  4800. void
  4801. write_text ()
  4802. {
  4803.   if (trace_files)
  4804.     fprintf (stderr, "Copying and relocating text:\n\n");
  4805.  
  4806.   lseek (outdesc, output_text_offset + text_header_size, 0);
  4807.  
  4808.   each_full_file (copy_text, 0);
  4809.   file_close ();
  4810.  
  4811.   if (trace_files)
  4812.     fprintf (stderr, "\n");
  4813.  
  4814.   padfile (text_pad, outdesc);
  4815. }
  4816.  
  4817. /* Read in all of the relocation information */
  4818.  
  4819. void
  4820. read_relocation ()
  4821. {
  4822.   each_full_file (read_file_relocation, 0);
  4823. }
  4824.  
  4825. /* Read in the relocation sections of ENTRY if necessary */
  4826.  
  4827. void
  4828. read_file_relocation (entry)
  4829.      struct file_entry *entry;
  4830. {
  4831.   register struct relocation_info *reloc;
  4832.   int desc;
  4833.   int read_return;
  4834.  
  4835.   desc = -1;
  4836.   if (!entry->textrel)
  4837.     {
  4838.       reloc = (struct relocation_info *) xmalloc (entry->text_reloc_size);
  4839.       desc = file_open (entry);
  4840.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4841.       if (entry->text_reloc_size != (read_return = read (desc, reloc, entry->text_reloc_size)))
  4842.     {
  4843.       fprintf (stderr, "Return from read: %d\n", read_return);
  4844.       fatal_with_file ("premature eof in text relocation of ", entry);
  4845.     }
  4846. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4847.       target_to_host_reloc_byte_order(reloc,
  4848.     entry->header.a_trsize/sizeof(*reloc));
  4849. #endif
  4850.       entry->textrel = reloc;
  4851.     }
  4852.  
  4853.   if (!entry->datarel)
  4854.     {
  4855.       reloc = (struct relocation_info *) xmalloc (entry->header.a_drsize);
  4856.       if (desc == -1) desc = file_open (entry);
  4857.       lseek (desc,
  4858.          text_offset (entry) + entry->header.a_text
  4859.          + entry->header.a_data + entry->header.a_trsize,
  4860.          L_SET);
  4861.       if (entry->header.a_drsize != read (desc, reloc, entry->header.a_drsize))
  4862.     fatal_with_file ("premature eof in data relocation of ", entry);
  4863. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4864.       target_to_host_reloc_byte_order(reloc,
  4865.     entry->header.a_drsize/sizeof(*reloc));
  4866. #endif
  4867.       entry->datarel = reloc;
  4868.     }
  4869. }
  4870.  
  4871. /* Read the text segment contents of ENTRY, relocate them,
  4872.    and write the result to the output file.
  4873.    If `-r', save the text relocation for later reuse.  */
  4874.  
  4875. void
  4876. copy_text (entry)
  4877.      struct file_entry *entry;
  4878. {
  4879.   register char *bytes;
  4880.   register int desc;
  4881.   register struct relocation_info *reloc;
  4882.  
  4883.   if (trace_files)
  4884.     prline_file_name (entry, stderr);
  4885.  
  4886.   desc = file_open (entry);
  4887.  
  4888.   /* Allocate space for the file's text section */
  4889.  
  4890.   bytes = (char *) alloca (entry->text_size);
  4891.  
  4892.   /* Deal with relocation information however is appropriate */
  4893.  
  4894.   if (entry->textrel)  reloc = entry->textrel;
  4895.   else if (output_style == OUTPUT_RELOCATABLE)
  4896.     {
  4897.       read_file_relocation (entry);
  4898.       reloc = entry->textrel;
  4899.     }
  4900.   else
  4901.     {
  4902.       reloc = (struct relocation_info *) alloca (entry->header.a_trsize);
  4903.       if (trace_files)
  4904.           printf("lseek to 0x%x (t_o= 0x%x, a_t= 0x%x, a_d= 0x%x)\n",
  4905.              text_offset(entry) + entry->header.a_text +
  4906.              entry->header.a_data, text_offset(entry),
  4907.              entry->header.a_text, entry->header.a_data);
  4908.       lseek (desc, text_offset (entry) + entry->header.a_text + entry->header.a_data, 0);
  4909.       if (entry->header.a_trsize != read (desc, reloc, entry->header.a_trsize))
  4910.     fatal_with_file ("premature eof in text relocation of ", entry);
  4911. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4912.       target_to_host_reloc_byte_order(reloc,
  4913.       entry->header.a_trsize/sizeof(*reloc));
  4914. #endif
  4915.     }
  4916.  
  4917.   /* Read the text section into core.  */
  4918.  
  4919.   lseek (desc, text_offset (entry), 0);
  4920.   if (entry->header.a_text != read (desc, bytes, entry->header.a_text))
  4921.     fatal_with_file ("premature eof in text section of ", entry);
  4922.  
  4923.  
  4924.   /* Relocate the text according to the text relocation.  */
  4925.  
  4926.   perform_relocation (bytes, entry->text_start_address, entry->header.a_text,
  4927.               reloc, entry->header.a_trsize, entry);
  4928.  
  4929.   /* Write the relocated text to the output file.  */
  4930.  
  4931.   mywrite (bytes, 1, entry->header.a_text, outdesc);
  4932. }
  4933.  
  4934. /* Relocate the data segment of each input file
  4935.    and write to the output file.  */
  4936.  
  4937. void
  4938. write_data ()
  4939. {
  4940.   if (trace_files)
  4941.     fprintf (stderr, "Copying and relocating data:\n\n");
  4942.  
  4943.   lseek (outdesc, output_data_offset, 0);
  4944.  
  4945.   each_full_file (copy_data, 0);
  4946.   file_close ();
  4947.  
  4948.   /* Write out the set element vectors.  See digest symbols for
  4949.      description of length of the set vector section.  */
  4950.  
  4951. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4952.   {
  4953.     int i;
  4954.     for (i = 0; i < 2 * set_symbol_count + set_vector_count; ++i) {
  4955.     fix_byte_order(&set_vectors[i], sizeof(*set_vectors));
  4956.     }
  4957.   }
  4958. #endif
  4959.  
  4960.   if (set_vector_count)
  4961.     mywrite (set_vectors, 2 * set_symbol_count + set_vector_count,
  4962.          sizeof (unsigned long), outdesc);
  4963.  
  4964.   if (trace_files)
  4965.     fprintf (stderr, "\n");
  4966.  
  4967.   padfile (data_pad, outdesc);
  4968. }
  4969.  
  4970. /* Read the data segment contents of ENTRY, relocate them,
  4971.    and write the result to the output file.
  4972.    If `-r', save the data relocation for later reuse.
  4973.    See comments in `copy_text'.  */
  4974.  
  4975. void
  4976. copy_data (entry)
  4977.      struct file_entry *entry;
  4978. {
  4979.   register struct relocation_info *reloc;
  4980.   register char *bytes;
  4981.   register int desc;
  4982.  
  4983.   if (trace_files)
  4984.     prline_file_name (entry, stderr);
  4985.  
  4986.   desc = file_open (entry);
  4987.  
  4988.   bytes = (char *) alloca (entry->data_size);
  4989.  
  4990.   if (entry->datarel) reloc = entry->datarel;
  4991.   else if (output_style == OUTPUT_RELOCATABLE)    /* Will need this again */
  4992.     {
  4993.       read_file_relocation (entry);
  4994.       reloc = entry->datarel;
  4995.     }
  4996.   else
  4997.     {
  4998.       reloc = (struct relocation_info *) alloca (entry->header.a_drsize);
  4999.       lseek (desc, text_offset (entry) + entry->header.a_text
  5000.          + entry->header.a_data + entry->header.a_trsize,
  5001.          0);
  5002.       if (entry->header.a_drsize != read (desc, reloc, entry->header.a_drsize))
  5003.     fatal_with_file ("premature eof in data relocation of ", entry);
  5004. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5005.       target_to_host_reloc_byte_order(reloc,
  5006.       entry->header.a_drsize/sizeof(*reloc));
  5007. #endif
  5008.     }
  5009.  
  5010.   lseek (desc, text_offset (entry) + entry->header.a_text, 0);
  5011.   if (entry->header.a_data != read (desc, bytes, entry->header.a_data))
  5012.     fatal_with_file ("premature eof in data section of ", entry);
  5013.  
  5014.   perform_relocation (bytes, entry->data_start_address - entry->header.a_text,
  5015.               entry->header.a_data, reloc, entry->header.a_drsize, entry);
  5016.  
  5017.   mywrite (bytes, 1, entry->header.a_data, outdesc);
  5018. }
  5019.  
  5020. /* Relocate ENTRY's text or data section contents.
  5021.    DATA is the address of the contents, in core.
  5022.    DATA_SIZE is the length of the contents.
  5023.    PC_RELOCATION is the difference between the address of the contents
  5024.      in the output file and its address in the input file.
  5025.    RELOC_INFO is the address of the relocation info, in core.
  5026.    RELOC_SIZE is its length in bytes.  */
  5027. /* This version is about to be severly hacked by Randy.  Hope it
  5028.    works afterwards. */
  5029. void
  5030. perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
  5031.      char *data;
  5032.      struct relocation_info *reloc_info;
  5033.      struct file_entry *entry;
  5034.      int pc_relocation;
  5035.      int data_size;
  5036.      int reloc_size;
  5037. {
  5038.   register struct relocation_info *p = reloc_info;
  5039.   struct relocation_info *end
  5040.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  5041.   int text_relocation = entry->text_start_address - entry->orig_text_address;
  5042.   int data_relocation = entry->data_start_address - entry->orig_data_address;
  5043.   int bss_relocation = entry->bss_start_address - entry->orig_bss_address;
  5044.  
  5045.   for (; p < end; p++)
  5046.     {
  5047.       register int relocation = 0;
  5048.       register int addr = RELOC_ADDRESS(p);
  5049.       register unsigned int mask = 0;
  5050.       register unsigned int x;
  5051.  
  5052.       if (addr >= data_size)
  5053.     fatal_with_file ("relocation address out of range in ", entry);
  5054.  
  5055.       if (RELOC_EXTERN_P(p))
  5056.     {
  5057.       int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
  5058.       symbol *sp = ((symbol *)
  5059.             (((struct nlist *)
  5060.               (((char *)entry->symbols) + symindex))
  5061.              ->n_un.n_name));
  5062.  
  5063. #ifdef N_INDR
  5064.       /* Resolve indirection */
  5065.       if ((sp->defined & ~N_EXT) == N_INDR)
  5066.         sp = (symbol *) sp->value;
  5067. #endif
  5068.  
  5069.       if (symindex >= entry->syms_size)
  5070.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5071.  
  5072.       /* If the symbol is undefined, leave it at zero.  */
  5073.       if (! sp->defined)
  5074.         relocation = 0;
  5075.       else
  5076.         relocation = sp->value;
  5077.     }
  5078.       else switch (RELOC_TYPE(p))
  5079.     {
  5080.     case N_TEXT:
  5081.     case N_TEXT | N_EXT:
  5082.       relocation = text_relocation;
  5083.       break;
  5084.  
  5085.     case N_DATA:
  5086.     case N_DATA | N_EXT:
  5087.       relocation = data_relocation;
  5088.       break;
  5089.  
  5090.     case N_BSS:
  5091.     case N_BSS | N_EXT:
  5092.       relocation = bss_relocation;
  5093.       break;
  5094.  
  5095.     case N_ABS:
  5096.     case N_ABS | N_EXT:
  5097.       /* Don't know why this code would occur, but apparently it does.  */
  5098.       break;
  5099.  
  5100.     default:
  5101.       fatal_with_file ("nonexternal relocation code invalid in ", entry);
  5102.     }
  5103. #if 0
  5104.       if (RELOC_PCREL_P(p))
  5105.     relocation -= pc_relocation;
  5106. #endif
  5107.  
  5108. #ifdef RELOC_ADD_EXTRA
  5109.       relocation += RELOC_ADD_EXTRA(p);
  5110.       if (output_style == OUTPUT_RELOCATABLE)
  5111.     {
  5112.       /* If this RELOC_ADD_EXTRA is 0, it means that the
  5113.          symbol was external and the relocation does not
  5114.          need a fixup here.  */
  5115.       if (RELOC_ADD_EXTRA (p))
  5116.         {
  5117.           if (! RELOC_PCREL_P (p))
  5118.         RELOC_ADD_EXTRA (p) = relocation;
  5119.           else
  5120.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  5121.         }
  5122. #if 1
  5123.       if (! RELOC_PCREL_P (p))
  5124.         {
  5125.           if ((int)p->r_type <= (int) RELOC_32
  5126.           || RELOC_EXTERN_P (p) == 0)
  5127.         RELOC_ADD_EXTRA (p) = relocation;
  5128.         }
  5129.       else if (RELOC_EXTERN_P (p))
  5130.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  5131. #endif
  5132.       continue;
  5133.     }
  5134. #endif
  5135. #if 1    
  5136.        if (RELOC_PCREL_P(p))
  5137.        relocation -= pc_relocation;
  5138. #endif
  5139.  
  5140.       relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  5141.  
  5142.       /* Unshifted mask for relocation */
  5143.       mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  5144.       mask |= mask - 1;
  5145.       relocation &= mask;
  5146.  
  5147.       /* Shift everything up to where it's going to be used */
  5148.       relocation <<= RELOC_TARGET_BITPOS(p);
  5149.       mask <<= RELOC_TARGET_BITPOS(p);
  5150.  
  5151.       switch (RELOC_TARGET_SIZE(p))
  5152.     {
  5153.     case 0:
  5154.       if (RELOC_MEMORY_SUB_P(p))
  5155.         relocation -= mask & *(char *) (data + addr);
  5156.       else if (RELOC_MEMORY_ADD_P(p))
  5157.         relocation += mask & *(char *) (data + addr);
  5158.       *(char *) (data + addr) &= ~mask;
  5159.       *(char *) (data + addr) |= relocation;
  5160.       break;
  5161.  
  5162.     case 1:
  5163. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5164.       x = ((unsigned char *) (data + addr))[1]
  5165.        | (((unsigned char *) (data + addr))[0] << 8);
  5166. #endif
  5167. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5168.       x = ((unsigned char *) (data + addr))[0]
  5169.        | (((unsigned char *) (data + addr))[1] << 8);
  5170. #endif
  5171.       if (RELOC_MEMORY_SUB_P(p))
  5172.         relocation -= mask & x;
  5173.       else if (RELOC_MEMORY_ADD_P(p))
  5174.         relocation += mask & x;
  5175.       x &= ~mask;
  5176.       x |= relocation;
  5177. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5178.       ((unsigned char *) (data + addr))[1] = x;
  5179.       ((unsigned char *) (data + addr))[0] = x >> 8;
  5180. #endif
  5181. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5182.       ((unsigned char *) (data + addr))[0] = x;
  5183.       ((unsigned char *) (data + addr))[1] = x >> 8;
  5184. #endif
  5185.       break;
  5186.  
  5187.     case 2:
  5188. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5189.       x = ((unsigned char *) (data + addr))[3]
  5190.        | (((unsigned char *) (data + addr))[2] << 8)
  5191.        | (((unsigned char *) (data + addr))[1] << 16)
  5192.        | (((unsigned char *) (data + addr))[0] << 24);
  5193. #endif
  5194. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5195.       x = ((unsigned char *) (data + addr))[0]
  5196.        | (((unsigned char *) (data + addr))[1] << 8)
  5197.        | (((unsigned char *) (data + addr))[2] << 16)
  5198.        | (((unsigned char *) (data + addr))[3] << 24);
  5199. #endif
  5200.           if (RELOC_MEMORY_SUB_P(p))
  5201.         relocation -= mask & x;
  5202.       else if (RELOC_MEMORY_ADD_P(p))
  5203.         relocation += mask & x;
  5204.       x &= ~mask;
  5205.       x |= relocation;
  5206. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5207.       ((unsigned char *) (data + addr))[3] = x;
  5208.       ((unsigned char *) (data + addr))[2] = x >> 8;
  5209.       ((unsigned char *) (data + addr))[1] = x >> 16;
  5210.       ((unsigned char *) (data + addr))[0] = x >> 24;
  5211. #endif
  5212. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5213.       ((unsigned char *) (data + addr))[0] = x;
  5214.       ((unsigned char *) (data + addr))[1] = x >> 8;
  5215.       ((unsigned char *) (data + addr))[2] = x >> 16;
  5216.       ((unsigned char *) (data + addr))[3] = x >> 24;
  5217. #endif
  5218.       break;
  5219.  
  5220.     default:
  5221.       fatal_with_file ("Unimplemented relocation field length in ", entry);
  5222.     }
  5223.     }
  5224. }
  5225.  
  5226. /* For OUTPUT_RELOCATABLE only: write out the relocation,
  5227.    relocating the addresses-to-be-relocated.  */
  5228.  
  5229. void coptxtrel (), copdatrel ();
  5230.  
  5231. void
  5232. write_rel ()
  5233. {
  5234.   register int i;
  5235.   register int count = 0;
  5236.  
  5237.   if (trace_files)
  5238.     fprintf (stderr, "Writing text relocation:\n\n");
  5239.  
  5240.   /* Assign each global symbol a sequence number, giving the order
  5241.      in which `write_syms' will write it.
  5242.      This is so we can store the proper symbolnum fields
  5243.      in relocation entries we write.  */
  5244.  
  5245.   for (i = 0; i < TABSIZE; i++)
  5246.     {
  5247.       symbol *sp;
  5248.       for (sp = symtab[i]; sp; sp = sp->link)
  5249.     if (sp->referenced || sp->defined)
  5250.       {
  5251.         sp->def_count = count++;
  5252. #ifndef NeXT
  5253.         /* Leave room for the reference required by N_INDR, if
  5254.            necessary.  */
  5255.         if ((sp->defined & ~N_EXT) == N_INDR)
  5256.           count++;
  5257. #endif
  5258.       }
  5259.     }
  5260.   /* Correct, because if (OUTPUT_RELOCATABLE), we will also be writing
  5261.      whatever indirect blocks we have.  */
  5262. #ifndef NeXT
  5263.   if (count != defined_global_sym_count
  5264.       + undefined_global_sym_count + global_indirect_count)
  5265. #else
  5266.   if (count != defined_global_sym_count
  5267.       + undefined_global_sym_count)
  5268. #endif
  5269.     fatal ("internal error");
  5270.  
  5271.   /* Write out the relocations of all files, remembered from copy_text.  */
  5272.  
  5273.   lseek (outdesc, output_trel_offset, 0);
  5274.   each_full_file (coptxtrel, 0);
  5275.  
  5276.   if (trace_files)
  5277.     fprintf (stderr, "\nWriting data relocation:\n\n");
  5278.  
  5279.   lseek (outdesc, output_drel_offset, 0);
  5280.   each_full_file (copdatrel, 0);
  5281.  
  5282.   if (trace_files)
  5283.     fprintf (stderr, "\n");
  5284. }
  5285.  
  5286. void
  5287. coptxtrel (entry)
  5288.      struct file_entry *entry;
  5289. {
  5290.   register struct relocation_info *p, *end;
  5291.   register int reloc = entry->text_start_address - text_start;
  5292.  
  5293.   p = entry->textrel;
  5294.   end = (struct relocation_info *) (entry->text_reloc_size + (char *) p);
  5295.   while (p < end)
  5296.     {
  5297.       RELOC_ADDRESS(p) += reloc;
  5298.       if (RELOC_EXTERN_P(p))
  5299.     {
  5300.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5301.       symbol *symptr = ((symbol *)
  5302.                 (((struct nlist *)
  5303.                   (((char *)entry->symbols) + symindex))
  5304.                  ->n_un.n_name));
  5305.  
  5306.       if (symindex >= entry->syms_size)
  5307.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5308.  
  5309. #ifdef N_INDR
  5310.       /* Resolve indirection.  */
  5311.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5312.         symptr = (symbol *) symptr->value;
  5313. #endif
  5314.  
  5315.       /* If the symbol is now defined, change the external relocation
  5316.          to an internal one.  */
  5317.  
  5318.       if (symptr->defined)
  5319.         {
  5320.           RELOC_EXTERN_P(p) = 0;
  5321.           RELOC_SYMBOL(p) = (symptr->defined & ~N_EXT);
  5322. #ifdef RELOC_ADD_EXTRA
  5323.           /* If we aren't going to be adding in the value in
  5324.              memory on the next pass of the loader, then we need
  5325.          to add it in from the relocation entry.  Otherwise
  5326.              the work we did in this pass is lost.  */
  5327.           if (!RELOC_MEMORY_ADD_P(p))
  5328.         RELOC_ADD_EXTRA (p) += symptr->value;
  5329. #endif
  5330.         }
  5331.       else
  5332.         /* Debugger symbols come first, so have to start this
  5333.            after them.  */
  5334.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5335.                  - defined_global_sym_count
  5336.                  - undefined_global_sym_count
  5337.                  - global_indirect_count);
  5338.     }
  5339.       p++;
  5340.     }
  5341. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5342.     host_to_target_reloc_byte_order((struct relocation_info *) entry->textrel,
  5343.     entry->header.a_trsize/sizeof(struct relocation_info));
  5344. #endif
  5345.   mywrite (entry->textrel, 1, entry->header.a_trsize, outdesc);
  5346. }
  5347.  
  5348. void
  5349. copdatrel (entry)
  5350.      struct file_entry *entry;
  5351. {
  5352.   register struct relocation_info *p, *end;
  5353.   /* Relocate the address of the relocation.
  5354.      Old address is relative to start of the input file's data section.
  5355.      New address is relative to start of the output file's data section.
  5356.  
  5357.      So the amount we need to relocate it by is the offset of this
  5358.      input file's data section within the output file's data section.  */
  5359.   register int reloc = entry->data_start_address - data_start;
  5360.  
  5361.   p = entry->datarel;
  5362.   end = (struct relocation_info *) (entry->data_reloc_size + (char *) p);
  5363.   while (p < end)
  5364.     {
  5365.       RELOC_ADDRESS(p) += reloc;
  5366.       if (RELOC_EXTERN_P(p))
  5367.     {
  5368.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5369.       symbol *symptr = ((symbol *)
  5370.                 (((struct nlist *)
  5371.                   (((char *)entry->symbols) + symindex))
  5372.                  ->n_un.n_name));
  5373.       int symtype;
  5374.  
  5375.       if (symindex >= entry->syms_size)
  5376.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5377.  
  5378. #ifdef N_INDR
  5379.       /* Resolve indirection.  */
  5380.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5381.         symptr = (symbol *) symptr->value;
  5382. #endif
  5383.  
  5384.       symtype = symptr->defined & ~N_EXT;
  5385.  
  5386.       if (force_common_definition
  5387.           || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
  5388.         {
  5389.           RELOC_EXTERN_P(p) = 0;
  5390.           RELOC_SYMBOL(p) = symtype;
  5391.         }
  5392.       else
  5393.         /* Debugger symbols come first, so have to start this
  5394.            after them.  */
  5395. #ifndef NeXT
  5396.         RELOC_SYMBOL(p)
  5397.           = (((symbol *)
  5398.           (((struct nlist *)
  5399.             (((char *)entry->symbols) + symindex))
  5400.            ->n_un.n_name))
  5401.          ->def_count
  5402.          + nsyms - defined_global_sym_count
  5403.          - undefined_global_sym_count
  5404.          - global_indirect_count);
  5405.     }
  5406.       p++;
  5407.     }
  5408. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5409.     host_to_target_reloc_byte_order((struct relocation_info *) entry->datarel,
  5410.     entry->header.a_drsize/sizeof(struct relocation_info));
  5411. #endif
  5412.   mywrite (entry->datarel, 1, entry->header.a_drsize, outdesc);
  5413. }
  5414.  
  5415. void write_file_syms ();
  5416. void write_string_table ();
  5417.  
  5418. /* Offsets and current lengths of symbol and string tables in output file. */
  5419.  
  5420. int symbol_table_offset;
  5421. int symbol_table_len;
  5422.  
  5423. /* Address in output file where string table starts.  */
  5424. int string_table_offset;
  5425.  
  5426. /* Offset within string table
  5427.    where the strings in `strtab_vector' should be written.  */
  5428. int string_table_len;
  5429.  
  5430. /* Total size of string table strings allocated so far,
  5431.    including strings in `strtab_vector'.  */
  5432. int strtab_size;
  5433.  
  5434. /* Vector whose elements are strings to be added to the string table.  */
  5435. char **strtab_vector;
  5436.  
  5437. /* Vector whose elements are the lengths of those strings.  */
  5438. int *strtab_lens;
  5439.  
  5440. /* Index in `strtab_vector' at which the next string will be stored.  */
  5441. int strtab_index;
  5442.  
  5443. /* Add the string NAME to the output file string table.
  5444.    Record it in `strtab_vector' to be output later.
  5445.    Return the index within the string table that this string will have.  */
  5446.  
  5447. int
  5448. assign_string_table_index (name)
  5449.      char *name;
  5450. {
  5451.   register int index = strtab_size;
  5452.   register int len = strlen (name) + 1;
  5453.  
  5454.   strtab_size += len;
  5455.   strtab_vector[strtab_index] = name;
  5456.   strtab_lens[strtab_index++] = len;
  5457.  
  5458.   return index;
  5459. }
  5460.  
  5461. FILE *outstream = (FILE *) 0;
  5462.  
  5463. /* Write the contents of `strtab_vector' into the string table.
  5464.    This is done once for each file's local&debugger symbols
  5465.    and once for the global symbols.  */
  5466.  
  5467. void
  5468. write_string_table ()
  5469. {
  5470.   register int i;
  5471.  
  5472.   lseek (outdesc, output_strs_offset + output_strs_size, 0);
  5473.  
  5474.   if (!outstream)
  5475.     outstream = fdopen (outdesc, "w");
  5476.  
  5477.   for (i = 0; i < strtab_index; i++)
  5478.     {
  5479.       fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
  5480.       output_strs_size += strtab_lens[i];
  5481.     }
  5482.  
  5483.   fflush (outstream);
  5484.  
  5485.   /* Report I/O error such as disk full.  */
  5486.   if (ferror (outstream))
  5487.     perror_name (output_filename);
  5488. }
  5489.  
  5490. /* Write the symbol table and string table of the output file.  */
  5491.  
  5492. void
  5493. write_syms ()
  5494. {
  5495.   /* Number of symbols written so far.  */
  5496.   int syms_written = 0;
  5497.   register int i;
  5498.   register symbol *sp;
  5499.  
  5500.   /* Buffer big enough for all the global symbols.  One
  5501.      extra struct for each indirect symbol to hold the extra reference
  5502.      following. */
  5503.   struct nlist *buf
  5504. #ifndef NeXT
  5505.     = (struct nlist *) alloca ((defined_global_sym_count
  5506.                 + undefined_global_sym_count
  5507.                 + global_indirect_count)
  5508.                    * sizeof (struct nlist));
  5509. #else
  5510.     = (struct nlist *) alloca ((defined_global_sym_count
  5511.                 + undefined_global_sym_count)
  5512.                    * sizeof (struct nlist));
  5513. #endif
  5514.   /* Pointer for storing into BUF.  */
  5515.   register struct nlist *bufp = buf;
  5516.  
  5517.   /* Size of string table includes the bytes that store the size.  */
  5518.   strtab_size = sizeof strtab_size;
  5519.  
  5520.   output_syms_size = 0;
  5521.   output_strs_size = strtab_size;
  5522.  
  5523.   if (strip_symbols == STRIP_ALL)
  5524.     return;
  5525.  
  5526.   /* Write the local symbols defined by the various files.  */
  5527.  
  5528.   each_file (write_file_syms, &syms_written);
  5529.   file_close ();
  5530.  
  5531.   /* Now write out the global symbols.  */
  5532.  
  5533.   /* Allocate two vectors that record the data to generate the string
  5534.      table from the global symbols written so far.  This must include
  5535.      extra space for the references following indirect outputs. */
  5536.  
  5537.   strtab_vector = (char **) alloca ((num_hash_tab_syms
  5538.                      + global_indirect_count) * sizeof (char *));
  5539.   strtab_lens = (int *) alloca ((num_hash_tab_syms
  5540.                  + global_indirect_count) * sizeof (int));
  5541.   strtab_index = 0;
  5542.  
  5543.   /* Scan the symbol hash table, bucket by bucket.  */
  5544.  
  5545.   for (i = 0; i < TABSIZE; i++)
  5546.     for (sp = symtab[i]; sp; sp = sp->link)
  5547.       {
  5548.     struct nlist nl;
  5549.  
  5550. #ifdef N_SECT
  5551.     nl.n_sect = 0;
  5552. #else
  5553.     nl.n_other = 0;
  5554. #endif
  5555.     nl.n_desc = 0;
  5556.  
  5557.     /* Compute a `struct nlist' for the symbol.  */
  5558.  
  5559.     if (sp->defined || sp->referenced)
  5560.       {
  5561.         /* common condition needs to be before undefined condition */
  5562.         /* because unallocated commons are set undefined in */
  5563.         /* digest_symbols */
  5564.         if (sp->defined > 1) /* defined with known type */
  5565.           {
  5566.         /* If the target of an indirect symbol has been
  5567.            defined and we are outputting an executable,
  5568.            resolve the indirection; it's no longer needed */
  5569.         if (output_style != OUTPUT_RELOCATABLE
  5570.             && ((sp->defined & ~N_EXT) == N_INDR)
  5571.             && (((symbol *) sp->value)->defined > 1))
  5572.           {
  5573.             symbol *newsp = (symbol *) sp->value;
  5574.             nl.n_type = newsp->defined;
  5575.             nl.n_value = newsp->value;
  5576.           }
  5577.         else
  5578.           {
  5579.             nl.n_type = sp->defined;
  5580.             if (sp->defined != (N_INDR | N_EXT))
  5581.               nl.n_value = sp->value;
  5582.             else
  5583.               nl.n_value = 0;
  5584.           }
  5585.           }
  5586.         else if (sp->max_common_size) /* defined as common but not allocated. */
  5587.           {
  5588.         /* happens only with -r and not -d */
  5589.         /* write out a common definition */
  5590.         nl.n_type = N_UNDF | N_EXT;
  5591.         nl.n_value = sp->max_common_size;
  5592.           }
  5593.         else if (!sp->defined)          /* undefined -- legit only if -r */
  5594.           {
  5595.         nl.n_type = N_UNDF | N_EXT;
  5596.         nl.n_value = 0;
  5597.           }
  5598.         else
  5599.           fatal ("internal error: %s defined in mysterious way", sp->name);
  5600.  
  5601.         /* Allocate string table space for the symbol name.  */
  5602.  
  5603.         nl.n_un.n_strx = assign_string_table_index (sp->name);
  5604.  
  5605.         /* Output to the buffer and count it.  */
  5606.  
  5607.         *bufp++ = nl;
  5608.         syms_written++;
  5609.         if (nl.n_type == (N_INDR | N_EXT))
  5610.           {
  5611.         struct nlist xtra_ref;
  5612.         xtra_ref.n_type == N_EXT | N_UNDF;
  5613.         xtra_ref.n_un.n_strx
  5614.           = assign_string_table_index (((symbol *) sp->value)->name);
  5615.         xtra_ref.n_other = 0;
  5616.         xtra_ref.n_desc = 0;
  5617.         xtra_ref.n_value = 0;
  5618.         *bufp++ = xtra_ref;
  5619.         syms_written++;
  5620.           }
  5621.       }
  5622.       }
  5623.  
  5624.   /* Output the buffer full of `struct nlist's.  */
  5625.  
  5626.   lseek (outdesc, symbol_table_offset + symbol_table_len, 0);
  5627. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5628.   {
  5629.     int i;
  5630.  
  5631.     for (i = 0; i < bufp - buf; ++i)
  5632.       {
  5633.         fix_byte_order(&buf[i].n_un.n_name, sizeof(buf->n_un.n_name));
  5634.     fix_byte_order(&buf[i].n_desc, sizeof(buf->n_desc));
  5635.     fix_byte_order(&buf[i].n_value, sizeof(buf->n_value));
  5636.       }
  5637.   }
  5638. #endif
  5639.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5640.   symbol_table_len += sizeof (struct nlist) * (bufp - buf);
  5641.  
  5642.   if (syms_written != nsyms)
  5643.     fatal ("internal error: wrong number of symbols written into output file", 0);
  5644.  
  5645.   if (symbol_table_offset + symbol_table_len != string_table_offset)
  5646.     fatal ("internal error: inconsistent symbol table length", 0);
  5647.  
  5648.   /* Now the total string table size is known, so write it.
  5649.      We are already positioned at the right place in the file.  */
  5650.  
  5651. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5652.   fix_byte_order(&strtab_size, sizeof(strtab_size));
  5653. #endif
  5654.  
  5655.   mywrite (&strtab_size, sizeof (int), 1, outdesc);  /* we're at right place */
  5656.  
  5657.   /* Write the strings for the global symbols.  */
  5658.  
  5659.   write_string_table ();
  5660. }
  5661.  
  5662. /* Write the local and debugger symbols of file ENTRY.
  5663.    Increment *SYMS_WRITTEN_ADDR for each symbol that is written.  */
  5664.  
  5665. /* Note that we do not combine identical names of local symbols.
  5666.    dbx or gdb would be confused if we did that.  */
  5667.  
  5668. void
  5669. write_file_syms (entry, syms_written_addr)
  5670.      struct file_entry *entry;
  5671.      int *syms_written_addr;
  5672. {
  5673.   register struct nlist *p = entry->symbols;
  5674.   register struct nlist *end = p + entry->syms_size / sizeof (struct nlist);
  5675.  
  5676.   /* Buffer to accumulate all the syms before writing them.
  5677.      It has one extra slot for the local symbol we generate here.  */
  5678.   struct nlist *buf
  5679.     = (struct nlist *) alloca (entry->syms_size + sizeof (struct nlist));
  5680.   register struct nlist *bufp = buf;
  5681.  
  5682.   /* Upper bound on number of syms to be written here.  */
  5683.   int max_syms = (entry->syms_size / sizeof (struct nlist)) + 1;
  5684.  
  5685.   /* Make tables that record, for each symbol, its name and its name's length.
  5686.      The elements are filled in by `assign_string_table_index'.  */
  5687.  
  5688.   strtab_vector = (char **) alloca (max_syms * sizeof (char *));
  5689.   strtab_lens = (int *) alloca (max_syms * sizeof (int));
  5690.   strtab_index = 0;
  5691.  
  5692.   /* Generate a local symbol for the start of this file's text.  */
  5693.  
  5694.   if (discard_locals != DISCARD_ALL)
  5695.     {
  5696.       struct nlist nl;
  5697.  
  5698. #if TARGET==TARGET_SEQUENT      
  5699.       nl.n_type = N_FN;
  5700. #else      
  5701.       nl.n_type = N_TEXT;
  5702. #endif
  5703.       nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
  5704.       nl.n_value = entry->text_start_address;
  5705.       nl.n_desc = 0;
  5706. #ifdef N_SECT
  5707.       nl.n_sect = 0;
  5708. #else
  5709.       nl.n_other = 0;
  5710. #endif
  5711.       *bufp++ = nl;
  5712.       (*syms_written_addr)++;
  5713.       entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
  5714.     }
  5715.  
  5716.   /* Read the file's string table.  */
  5717.  
  5718.   entry->strings = (char *) alloca (entry->strs_size);
  5719.   read_entry_strings (file_open (entry), entry);
  5720.  
  5721.   for (; p < end; p++)
  5722.     {
  5723.       register int type = p->n_type;
  5724.       register int write = 0;
  5725.  
  5726.       /* WRITE gets 1 for a non-global symbol that should be written.  */
  5727.  
  5728.  
  5729.       if (SET_ELEMENT_P (type))    /* This occurs even if global.  These */
  5730.                 /* types of symbols are never written */
  5731.                 /* globally, though they are stored */
  5732.                 /* globally.  */
  5733.         write = output_style == OUTPUT_RELOCATABLE;
  5734.       else if (!(type & (N_STAB | N_EXT)))
  5735.         /* ordinary local symbol */
  5736.     write = ((discard_locals != DISCARD_ALL)
  5737.          && !(discard_locals == DISCARD_L &&
  5738.               (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
  5739.          && type != N_WARNING);
  5740.       else if (!(type & N_EXT))
  5741.     /* debugger symbol */
  5742.         write = (strip_symbols == STRIP_NONE);
  5743.  
  5744.       if (write)
  5745.     {
  5746.       /* If this symbol has a name,
  5747.          allocate space for it in the output string table.  */
  5748.  
  5749.       if (p->n_un.n_strx)
  5750.         p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
  5751.                             + entry->strings);
  5752.  
  5753.       /* Output this symbol to the buffer and count it.  */
  5754.  
  5755.       *bufp++ = *p;
  5756.       (*syms_written_addr)++;
  5757.     }
  5758.     }
  5759.  
  5760.   /* All the symbols are now in BUF; write them.  */
  5761.  
  5762.   lseek (outdesc, symbol_table_offset + symbol_table_len, 0);
  5763. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5764.   {
  5765.     int i;
  5766.  
  5767.     for (i = 0; i < bufp - buf; ++i)
  5768.       {
  5769.     fix_byte_order(&buf[i].n_un.n_name, sizeof(buf->n_un.n_name));
  5770.     fix_byte_order(&buf[i].n_desc, sizeof(buf->n_desc));
  5771.     fix_byte_order(&buf[i].n_value, sizeof(buf->n_value));
  5772.       }
  5773.   }
  5774. #endif
  5775.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5776.   symbol_table_len += sizeof (struct nlist) * (bufp - buf);
  5777.  
  5778.   /* Write the string-table data for the symbols just written,
  5779.      using the data in vectors `strtab_vector' and `strtab_lens'.  */
  5780.  
  5781.   write_string_table ();
  5782.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  5783. }
  5784.  
  5785. /* Copy any GDB symbol segments from the input files to the output file.
  5786.    The contents of the symbol segment is copied without change
  5787.    except that we store some information into the beginning of it.  */
  5788.  
  5789. void write_file_symseg ();
  5790.  
  5791. void
  5792. write_symsegs ()
  5793. {
  5794.   lseek (outdesc, output_symseg_offset, 0);
  5795.   each_file (write_file_symseg, 0);
  5796. }
  5797.  
  5798. void
  5799. write_file_symseg (entry)
  5800.      struct file_entry *entry;
  5801. {
  5802.   char buffer[4096];
  5803.   struct symbol_root root;
  5804.   int indesc, len, total;
  5805.  
  5806.   if (entry->symseg_size == 0)
  5807.     return;
  5808.  
  5809.   output_symseg_size += entry->symseg_size;
  5810.  
  5811.   /* This entry has a symbol segment.  Read the root of the segment.  */
  5812.  
  5813.   indesc = file_open (entry);
  5814.   lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
  5815.   if (sizeof root != read (indesc, &root, sizeof root))
  5816.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  5817.  
  5818. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5819.   fix_symbol_root_byte_order(&root);
  5820. #endif
  5821.  
  5822.   /* Store some relocation info into the root.  */
  5823.  
  5824.   root.ldsymoff = entry->local_syms_offset;
  5825.   root.textrel = entry->text_start_address - entry->orig_text_address;
  5826.   root.datarel = entry->data_start_address - entry->orig_data_address;
  5827.   root.bssrel = entry->bss_start_address - entry->orig_bss_address;
  5828.   root.databeg = entry->data_start_address - root.datarel;
  5829.   root.bssbeg = entry->bss_start_address - root.bssrel;
  5830.  
  5831.   /* Write the modified root into the output file.  */
  5832.  
  5833. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5834.   fix_symbol_root_byte_order(&root);
  5835. #endif
  5836.   mywrite (&root, sizeof root, 1, outdesc);
  5837.  
  5838.   /* Copy the rest of the symbol segment unchanged.  */
  5839.  
  5840.   if (entry->superfile)
  5841.     {
  5842.       /* Library member: number of bytes to copy is determined
  5843.      from the member's total size.  */
  5844.  
  5845.       int total = entry->total_size - entry->symseg_offset - sizeof root;
  5846.  
  5847.       while (total > 0)
  5848.     {
  5849.       len = read (indesc, buffer, min (sizeof buffer, total));
  5850.  
  5851.       if (len != min (sizeof buffer, total))
  5852.         fatal_with_file ("premature end of file in symbol segment of ", entry);
  5853.       total -= len;
  5854.       mywrite (buffer, len, 1, outdesc);
  5855.     }
  5856.     }
  5857.   else
  5858.     {
  5859.       /* A separate file: copy until end of file.  */
  5860.  
  5861.       while (len = read (indesc, buffer, sizeof buffer))
  5862.     {
  5863.       mywrite (buffer, len, 1, outdesc);
  5864.       if (len < sizeof buffer)
  5865.         break;
  5866.     }
  5867.     }
  5868.  
  5869.   file_close ();
  5870. }
  5871.  
  5872. /* Create the symbol table entries for `etext', `edata' and `end'.  */
  5873.  
  5874. void
  5875. symtab_init ()
  5876. {
  5877. #ifndef nounderscore
  5878.   edata_symbol = getsym ("_edata");
  5879.   etext_symbol = getsym ("_etext");
  5880.   end_symbol = getsym ("_end");
  5881. #else
  5882.   edata_symbol = getsym ("edata");
  5883.   etext_symbol = getsym ("etext");
  5884.   end_symbol = getsym ("end");
  5885. #endif
  5886.  
  5887. #if TARGET_MACHINE==TARGET_SUN4 || TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  5888.   {
  5889.     symbol *dynamic_symbol = getsym ("__DYNAMIC");
  5890.     dynamic_symbol->defined = N_ABS | N_EXT;
  5891.     dynamic_symbol->referenced = 1;
  5892.     dynamic_symbol->value = 0;
  5893.   }
  5894. #endif
  5895. #if TARGET_MACHINE==TARGET_SEQUENT
  5896.   {
  5897.     symbol *_387_flt_symbol = getsym ("_387_flt");
  5898.     _387_flt_symbol->defined = N_ABS | N_EXT;
  5899.     _387_flt_symbol->referenced = 1;
  5900.     _387_flt_symbol->value = 0;
  5901.   }
  5902. #endif
  5903.  
  5904.   edata_symbol->defined = N_DATA | N_EXT;
  5905.   etext_symbol->defined = N_TEXT | N_EXT;
  5906.   end_symbol->defined = N_BSS | N_EXT;
  5907.  
  5908.   edata_symbol->referenced = 1;
  5909.   etext_symbol->referenced = 1;
  5910.   end_symbol->referenced = 1;
  5911. }
  5912.  
  5913. /* Compute the hash code for symbol name KEY.  */
  5914.  
  5915. int
  5916. hash_string (key)
  5917.      char *key;
  5918. {
  5919.   register char *cp;
  5920.   register int k;
  5921.  
  5922.   cp = key;
  5923.   k = 0;
  5924.   while (*cp)
  5925.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  5926.  
  5927.   return k;
  5928. }
  5929.  
  5930. /* Get the symbol table entry for the global symbol named KEY.
  5931.    Create one if there is none.  */
  5932.  
  5933. symbol *
  5934. getsym (key)
  5935.      char *key;
  5936. {
  5937.   register int hashval;
  5938.   register symbol *bp;
  5939.  
  5940.   /* Determine the proper bucket.  */
  5941.  
  5942.   hashval = hash_string (key) % TABSIZE;
  5943.  
  5944.   /* Search the bucket.  */
  5945.  
  5946.   for (bp = symtab[hashval]; bp; bp = bp->link)
  5947.     if (! strcmp (key, bp->name))
  5948.       return bp;
  5949.  
  5950.   /* Nothing was found; create a new symbol table entry.  */
  5951.  
  5952.   bp = (symbol *) xmalloc (sizeof (symbol));
  5953.   bp->refs = 0;
  5954.   bp->name = (char *) xmalloc (strlen (key) + 1);
  5955.   strcpy (bp->name, key);
  5956.   bp->defined = 0;
  5957.   bp->referenced = 0;
  5958.   bp->trace = 0;
  5959.   bp->value = 0;
  5960.   bp->max_common_size = 0;
  5961.   bp->warning = 0;
  5962.   bp->undef_refs = 0;
  5963.   bp->multiply_defined = 0;
  5964.  
  5965.   /* Add the entry to the bucket.  */
  5966.  
  5967.   bp->link = symtab[hashval];
  5968.   symtab[hashval] = bp;
  5969.  
  5970.   ++num_hash_tab_syms;
  5971.  
  5972.   return bp;
  5973. }
  5974.  
  5975. /* Like `getsym' but return 0 if the symbol is not already known.  */
  5976.  
  5977. symbol *
  5978. getsym_soft (key)
  5979.      char *key;
  5980. {
  5981.   register int hashval;
  5982.   register symbol *bp;
  5983.  
  5984.   /* Determine which bucket.  */
  5985.  
  5986.   hashval = hash_string (key) % TABSIZE;
  5987.  
  5988.   /* Search the bucket.  */
  5989.  
  5990.   for (bp = symtab[hashval]; bp; bp = bp->link)
  5991.     if (! strcmp (key, bp->name))
  5992.       return bp;
  5993.  
  5994.   return 0;
  5995. }
  5996.  
  5997. /* Report a usage error.
  5998.    Like fatal except prints a usage summary.  */
  5999.  
  6000. void
  6001. usage (string, arg)
  6002.      char *string, *arg;
  6003. {
  6004.   if (string)
  6005.     {
  6006.       fprintf (stderr, "%s: ", progname);
  6007.       fprintf (stderr, string, arg);
  6008.       fprintf (stderr, "\n");
  6009.     }
  6010.   fprintf (stderr, "\
  6011. Usage: %s [-d] [-dc] [-dp] [-e symbol] [-l lib] [-n] [-noinhibit-exec]\n\
  6012.        [-nostdlib] [-o file] [-r] [-s] [-t] [-u symbol] [-x] [-y symbol]\n\
  6013.        [-z] [-A file] [-Bstatic] [-D size] [-L libdir] [-M] [-N]\n\
  6014.        [-S] [-T[{text,data}] addr] [-V prefix] [-X] [file...]\n",
  6015.        progname);
  6016.   exit (1);
  6017. }
  6018.  
  6019. /* Report a fatal error.
  6020.    STRING is a printf format string and ARG is one arg for it.  */
  6021.  
  6022. void
  6023. fatal (string, arg)
  6024.      char *string, *arg;
  6025. {
  6026.   fprintf (stderr, "%s: ", progname);
  6027.   fprintf (stderr, string, arg);
  6028.   fprintf (stderr, "\n");
  6029.   exit (1);
  6030. }
  6031.  
  6032. /* Report a fatal error.  The error message is STRING
  6033.    followed by the filename of ENTRY.  */
  6034.  
  6035. void
  6036. fatal_with_file (string, entry)
  6037.      char *string;
  6038.      struct file_entry *entry;
  6039. {
  6040.   fprintf (stderr, "%s: ", progname);
  6041.   fprintf (stderr, string);
  6042.   print_file_name (entry, stderr);
  6043.   fprintf (stderr, "\n");
  6044.   exit (1);
  6045. }
  6046.  
  6047. /* Report a fatal error using the message for the last failed system call,
  6048.    followed by the string NAME.  */
  6049.  
  6050. void
  6051. perror_name (name)
  6052.      char *name;
  6053. {
  6054.   extern int errno, sys_nerr;
  6055.   extern char *sys_errlist[];
  6056.   char *s;
  6057.  
  6058.   if (errno < sys_nerr)
  6059.     s = concat ("", sys_errlist[errno], " for %s");
  6060.   else
  6061.     s = "cannot open %s";
  6062.   fatal (s, name);
  6063. }
  6064.  
  6065. /* Report a fatal error using the message for the last failed system call,
  6066.    followed by the name of file ENTRY.  */
  6067.  
  6068. void
  6069. perror_file (entry)
  6070.      struct file_entry *entry;
  6071. {
  6072.   extern int errno, sys_nerr;
  6073.   extern char *sys_errlist[];
  6074.   char *s;
  6075.  
  6076.   if (errno < sys_nerr)
  6077.     s = concat ("", sys_errlist[errno], " for ");
  6078.   else
  6079.     s = "cannot open ";
  6080.   fatal_with_file (s, entry);
  6081. }
  6082.  
  6083. /* Report a nonfatal error.
  6084.    STRING is a format for printf, and ARG1 ... ARG3 are args for it.  */
  6085.  
  6086. void
  6087. error (string, arg1, arg2, arg3)
  6088.      char *string, *arg1, *arg2, *arg3;
  6089. {
  6090.   fprintf (stderr, "%s: ", progname);
  6091.   fprintf (stderr, string, arg1, arg2, arg3);
  6092.   fprintf (stderr, "\n");
  6093. }
  6094.  
  6095.  
  6096. /* Output COUNT*ELTSIZE bytes of data at BUF
  6097.    to the descriptor DESC.  */
  6098.  
  6099. void
  6100. mywrite (buf, count, eltsize, desc)
  6101.      char *buf;
  6102.      int count;
  6103.      int eltsize;
  6104.      int desc;
  6105. {
  6106.   register int val;
  6107.   register int bytes = count * eltsize;
  6108.  
  6109.   while (bytes > 0)
  6110.     {
  6111.       val = write (desc, buf, bytes);
  6112.       if (val <= 0)
  6113.     perror_name (output_filename);
  6114.       buf += val;
  6115.       bytes -= val;
  6116.     }
  6117. }
  6118.  
  6119. /* Output PADDING zero-bytes to descriptor OUTDESC.
  6120.    PADDING may be negative; in that case, do nothing.  */
  6121.  
  6122. void
  6123. padfile (padding, outdesc)
  6124.      int padding;
  6125.      int outdesc;
  6126. {
  6127.   register char *buf;
  6128.   if (padding <= 0)
  6129.     return;
  6130.  
  6131.   buf = (char *) alloca (padding);
  6132.   bzero (buf, padding);
  6133.   mywrite (buf, padding, 1, outdesc);
  6134. }
  6135.  
  6136. /* Return a newly-allocated string
  6137.    whose contents concatenate the strings S1, S2, S3.  */
  6138.  
  6139. char *
  6140. concat (s1, s2, s3)
  6141.      char *s1, *s2, *s3;
  6142. {
  6143.   register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  6144.   register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  6145.  
  6146.   strcpy (result, s1);
  6147.   strcpy (result + len1, s2);
  6148.   strcpy (result + len1 + len2, s3);
  6149.   result[len1 + len2 + len3] = 0;
  6150.  
  6151.   return result;
  6152. }
  6153.  
  6154. /* Parse the string ARG using scanf format FORMAT, and return the result.
  6155.    If it does not parse, report fatal error
  6156.    generating the error message using format string ERROR and ARG as arg.  */
  6157.  
  6158. int
  6159. parse (arg, format, error)
  6160.      char *arg, *format;
  6161. {
  6162.   int x;
  6163.   if (1 != sscanf (arg, format, &x))
  6164.     fatal (error, arg);
  6165.   return x;
  6166. }
  6167.  
  6168. /* Like malloc but get fatal error if memory is exhausted.  */
  6169.  
  6170. char *
  6171. xmalloc (size)
  6172.      int size;
  6173. {
  6174.   register char *result = malloc (size);
  6175.   if (!result)
  6176.     fatal ("virtual memory exhausted", 0);
  6177.   return result;
  6178. }
  6179.  
  6180. /* Like realloc but get fatal error if memory is exhausted.  */
  6181.  
  6182. char *
  6183. xrealloc (ptr, size)
  6184.      char *ptr;
  6185.      int size;
  6186. {
  6187.   register char *result = realloc (ptr, size);
  6188.   if (!result)
  6189.     fatal ("virtual memory exhausted", 0);
  6190.   return result;
  6191. }
  6192.  
  6193. #ifdef USG
  6194.  
  6195. void
  6196. bzero (p, n)
  6197.      char *p;
  6198. {
  6199.   memset (p, 0, n);
  6200. }
  6201.  
  6202. void
  6203. bcopy (from, to, n)
  6204.      char *from, *to;
  6205. {
  6206.   memcpy (to, from, n);
  6207. }
  6208.  
  6209. getpagesize ()
  6210. {
  6211.   return (4096);
  6212. }
  6213.  
  6214. #endif
  6215.  
  6216. #if defined(sun) && defined(sparc)
  6217. int
  6218. getpagesize ()
  6219. {
  6220.   return 8192;
  6221. }
  6222. #endif
  6223.  
  6224.  
  6225. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  6226.  
  6227. static void
  6228. fix_byte_order(p, n)
  6229.     char *p;
  6230.     int n;
  6231. {
  6232.     char t;
  6233.  
  6234.     switch (n) {
  6235.  
  6236.     case 1:
  6237.     return;
  6238.  
  6239.     case 2:
  6240.     t = p[0];
  6241.     p[0] = p[1];
  6242.     p[1] = t;
  6243.     return;
  6244.  
  6245.     case 4:
  6246.     t = p[0];
  6247.     p[0] = p[3];
  6248.     p[3] = t;
  6249.     t = p[1];
  6250.     p[1] = p[2];
  6251.     p[2] = t;
  6252.     return;
  6253.  
  6254.     default:
  6255.     fatal("Internal Error in fix_byte_order, n = %d\n", 0);
  6256.     }
  6257. }
  6258.  
  6259. static void
  6260. fix_exec_header_byte_order(execP)
  6261.     struct exec *execP;
  6262. {
  6263.  
  6264. #if TARGET_MACHINE==TARGET_SUN4
  6265.     if (N_BADMAG(*execP)) {
  6266.     u_char c = * (u_char *) execP;
  6267.     execP->a_dynamic = c & 1;
  6268.     execP->a_toolversion = c >> 1;
  6269.     } else {
  6270.     u_char c = execP->a_toolversion | (execP->a_dynamic << 7);
  6271.     * (u_char *) execP = c;
  6272.     }
  6273. #elif TARGET_MACHINE!=TARGET_SEQUENT
  6274.     fix_byte_order(&execP->a_machtype, sizeof(execP->a_machtype));
  6275. #endif
  6276.     fix_byte_order(&execP->a_magic,    sizeof(execP->a_magic));
  6277.     fix_byte_order(&execP->a_text,     sizeof(execP->a_text));
  6278.     fix_byte_order(&execP->a_data,     sizeof(execP->a_data));
  6279.     fix_byte_order(&execP->a_bss,      sizeof(execP->a_bss));
  6280.     fix_byte_order(&execP->a_syms,     sizeof(execP->a_syms));
  6281.     fix_byte_order(&execP->a_entry,    sizeof(execP->a_entry));
  6282.     fix_byte_order(&execP->a_trsize,   sizeof(execP->a_trsize));
  6283.     fix_byte_order(&execP->a_drsize,   sizeof(execP->a_drsize));
  6284.     return;
  6285. }
  6286.  
  6287. static void
  6288. fix_symbol_byte_order(p, size)
  6289.     struct nlist *p;
  6290.     int size;
  6291. {
  6292.     int n;
  6293.  
  6294.     for (n = size / sizeof(*p); --n >= 0; ++p) {
  6295.     fix_byte_order(&p->n_un, sizeof(p->n_un));
  6296.     fix_byte_order(&p->n_desc, sizeof(p->n_desc));
  6297.     fix_byte_order(&p->n_value, sizeof(p->n_value));
  6298.     }
  6299.     return;
  6300. }
  6301.  
  6302. static void
  6303. target_to_host_reloc_byte_order(relocP, nrelocs)
  6304.     struct relocation_info *relocP;
  6305.     int nrelocs;
  6306. {
  6307.     u_char c[4];
  6308.  
  6309. #if TARGET_BYTE_ORDER==BIG_ENDIAN && HOST_BYTE_ORDER==LITTLE_ENDIAN
  6310.     for (; --nrelocs >= 0; ++relocP) {
  6311.     fix_byte_order(&relocP->r_address, sizeof(relocP->r_address));
  6312.     c[0] = ((u_char *) relocP)[4];
  6313.     c[1] = ((u_char *) relocP)[5];
  6314.     c[2] = ((u_char *) relocP)[6];
  6315.     c[3] = ((u_char *) relocP)[7];
  6316.     ((u_long *) relocP)[1] = 0;
  6317. #if TARGET_MACHINE==TARGET_SUN4
  6318.     relocP->r_index = (c[0] << 16) | (c[1] << 8) | c[2];
  6319.     relocP->r_type = (enum reloc_type) (c[3] & 0x1f);
  6320.     relocP->r_extern = (c[3] & 0x80) >> 7;
  6321.     fix_byte_order(&relocP->r_addend, sizeof(relocP->r_addend));
  6322. #else
  6323.     relocP->r_symbolnum = (c[0] << 16) | (c[1] << 8) | c[2];
  6324.     relocP->r_pcrel = (c[3] >> 7) & 1;
  6325.     relocP->r_length = (c[3] >> 5) & 3;
  6326.     relocP->r_extern = (c[3] >> 4) & 1;
  6327. #endif
  6328.     }
  6329. #endif
  6330.     return;
  6331. }
  6332.  
  6333. static void
  6334. host_to_target_reloc_byte_order(relocP, nrelocs)
  6335.     struct relocation_info *relocP;
  6336.     int nrelocs;
  6337. {
  6338.     u_char c[4];
  6339.  
  6340. #if TARGET_BYTE_ORDER==BIG_ENDIAN && HOST_BYTE_ORDER==LITTLE_ENDIAN
  6341.     for (; --nrelocs >= 0; ++relocP) {
  6342.     fix_byte_order(&relocP->r_address, sizeof(relocP->r_address));
  6343. #if TARGET_MACHINE==TARGET_SUN4
  6344.     c[0] = (relocP->r_index >> 16);
  6345.     c[1] = (relocP->r_index >> 8);
  6346.     c[2] = relocP->r_index;
  6347.     c[3] = (u_char) relocP->r_type | (relocP->r_extern << 7);
  6348.     fix_byte_order(&relocP->r_addend, sizeof(relocP->r_addend));
  6349. #else
  6350.     c[0] = (relocP->r_symbolnum >> 16);
  6351.     c[1] = (relocP->r_symbolnum >> 8);
  6352.     c[2] = relocP->r_symbolnum;
  6353.     c[3] = (relocP->r_pcrel << 7) |
  6354.         (relocP->r_length << 5) | (relocP->r_extern << 4);
  6355. #endif
  6356.     ((u_char *) relocP)[4] = c[0];
  6357.     ((u_char *) relocP)[5] = c[1];
  6358.     ((u_char *) relocP)[6] = c[2];
  6359.     ((u_char *) relocP)[7] = c[3];
  6360.     }
  6361. #endif
  6362.     return;
  6363. }
  6364.  
  6365. static void
  6366. fix_symbol_root_byte_order(p)
  6367.     struct symbol_root *p;
  6368. {
  6369.  
  6370.     fix_byte_order(&p->format, sizeof(p->format));
  6371.     fix_byte_order(&p->length, sizeof(p->length));
  6372.     fix_byte_order(&p->ldsymoff, sizeof(p->ldsymoff));
  6373.     fix_byte_order(&p->textrel, sizeof(p->textrel));
  6374.     fix_byte_order(&p->datarel, sizeof(p->datarel));
  6375.     fix_byte_order(&p->bssrel, sizeof(p->bssrel));
  6376.     fix_byte_order(&p->filename, sizeof(p->filename));
  6377.     fix_byte_order(&p->filedir, sizeof(p->filedir));
  6378.     fix_byte_order(&p->blockvector, sizeof(p->blockvector));
  6379.     fix_byte_order(&p->typevector, sizeof(p->typevector));
  6380.     fix_byte_order(&p->language, sizeof(p->language));
  6381.     fix_byte_order(&p->version, sizeof(p->version));
  6382.     fix_byte_order(&p->compilation, sizeof(p->compilation));
  6383.     fix_byte_order(&p->databeg, sizeof(p->databeg));
  6384.     fix_byte_order(&p->bssbeg, sizeof(p->bssbeg));
  6385.     fix_byte_order(&p->sourcevector, sizeof(p->sourcevector));
  6386.     return;
  6387. }
  6388.  
  6389. #endif
  6390.  
  6391.